PageRenderTime 47ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/forum/Sources/Security.php

https://github.com/leftnode/nooges.com
PHP | 991 lines | 651 code | 119 blank | 221 comment | 193 complexity | 1418baaac6607e23480a742ca6837078 MD5 | raw file
  1. <?php
  2. /**********************************************************************************
  3. * Security.php *
  4. ***********************************************************************************
  5. * SMF: Simple Machines Forum *
  6. * Open-Source Project Inspired by Zef Hemel (zef@zefhemel.com) *
  7. * =============================================================================== *
  8. * Software Version: SMF 2.0 RC2 *
  9. * Software by: Simple Machines (http://www.simplemachines.org) *
  10. * Copyright 2006-2009 by: Simple Machines LLC (http://www.simplemachines.org) *
  11. * 2001-2006 by: Lewis Media (http://www.lewismedia.com) *
  12. * Support, News, Updates at: http://www.simplemachines.org *
  13. ***********************************************************************************
  14. * This program is free software; you may redistribute it and/or modify it under *
  15. * the terms of the provided license as published by Simple Machines LLC. *
  16. * *
  17. * This program is distributed in the hope that it is and will be useful, but *
  18. * WITHOUT ANY WARRANTIES; without even any implied warranty of MERCHANTABILITY *
  19. * or FITNESS FOR A PARTICULAR PURPOSE. *
  20. * *
  21. * See the "license.txt" file for details of the Simple Machines license. *
  22. * The latest version can always be found at http://www.simplemachines.org. *
  23. **********************************************************************************/
  24. if (!defined('SMF'))
  25. die('Hacking attempt...');
  26. /* This file has the very important job of insuring forum security. This
  27. task includes banning and permissions, namely. It does this by providing
  28. the following functions:
  29. void validateSession()
  30. - makes sure the user is who they claim to be by requiring a
  31. password to be typed in every hour.
  32. - is turned on and off by the securityDisable setting.
  33. - uses the adminLogin() function of Subs-Auth.php if they need to
  34. login, which saves all request (post and get) data.
  35. void is_not_guest(string message = '')
  36. - checks if the user is currently a guest, and if so asks them to
  37. login with a message telling them why.
  38. - message is what to tell them when asking them to login.
  39. void is_not_banned(bool force_check = false)
  40. - checks if the user is banned, and if so dies with an error.
  41. - caches this information for optimization purposes.
  42. - forces a recheck if force_check is true.
  43. void banPermissions()
  44. - applies any states of banning by removing permissions the user
  45. cannot have.
  46. void log_ban(array ban_ids = array(), string email = null)
  47. - log the current user in the ban logs.
  48. - increment the hit counters for the specified ban ID's (if any.)
  49. void isBannedEmail(string email, string restriction, string error)
  50. - check if a given email is banned.
  51. - performs an immediate ban if the turns turns out positive.
  52. string checkSession(string type = 'post', string from_action = none,
  53. is_fatal = true)
  54. - checks the current session, verifying that the person is who he or
  55. she should be.
  56. - also checks the referrer to make sure they didn't get sent here.
  57. - depends on the disableCheckUA setting, which is usually missing.
  58. - will check GET, POST, or REQUEST depending on the passed type.
  59. - also optionally checks the referring action if passed. (note that
  60. the referring action must be by GET.)
  61. - returns the error message if is_fatal is false.
  62. bool checkSubmitOnce(string action, bool is_fatal = true)
  63. - registers a sequence number for a form.
  64. - checks whether a submitted sequence number is registered in the
  65. current session.
  66. - depending on the value of is_fatal shows an error or returns true or
  67. false.
  68. - frees a sequence number from the stack after it's been checked.
  69. - frees a sequence number without checking if action == 'free'.
  70. bool allowedTo(string permission, array boards = current)
  71. - checks whether the user is allowed to do permission. (ie. post_new.)
  72. - if boards is specified, checks those boards instead of the current
  73. one.
  74. - always returns true if the user is an administrator.
  75. - returns true if he or she can do it, false otherwise.
  76. void isAllowedTo(string permission, array boards = current)
  77. - uses allowedTo() to check if the user is allowed to do permission.
  78. - checks the passed boards or current board for the permission.
  79. - if they are not, it loads the Errors language file and shows an
  80. error using $txt['cannot_' . $permission].
  81. - if they are a guest and cannot do it, this calls is_not_guest().
  82. array boardsAllowedTo(string permission, bool check_access = false)
  83. - returns a list of boards on which the user is allowed to do the
  84. specified permission.
  85. - returns an array with only a 0 in it if the user has permission
  86. to do this on every board.
  87. - returns an empty array if he or she cannot do this on any board.
  88. - if check_access is true will also make sure the group has proper access to that board.
  89. string showEmailAddress(string userProfile_hideEmail, int userProfile_id)
  90. - returns whether an email address should be shown and how.
  91. - possible outcomes are
  92. 'yes': show the full email address
  93. 'yes_permission_override': show the full email address, either you
  94. are a moderator or it's your own email address.
  95. 'no_through_forum': don't show the email address, but do allow
  96. things to be mailed using the built-in forum mailer.
  97. 'no': keep the email address hidden.
  98. */
  99. // Check if the user is who he/she says he is
  100. function validateSession()
  101. {
  102. global $modSettings, $sourcedir, $user_info, $sc, $user_settings;
  103. // We don't care if the option is off, because Guests should NEVER get past here.
  104. is_not_guest();
  105. // If we're using XML give an additional ten minutes grace as an admin can't log on in XML mode.
  106. $refreshTime = isset($_GET['xml']) ? 4200 : 3600;
  107. // Is the security option off? Or are they already logged in?
  108. if (!empty($modSettings['securityDisable']) || (!empty($_SESSION['admin_time']) && $_SESSION['admin_time'] + $refreshTime >= time()))
  109. return;
  110. require_once($sourcedir . '/Subs-Auth.php');
  111. // Hashed password, ahoy!
  112. if (isset($_POST['admin_hash_pass']) && strlen($_POST['admin_hash_pass']) == 40)
  113. {
  114. checkSession();
  115. $good_password = false;
  116. if (isset($modSettings['integrate_verify_password']) && function_exists($modSettings['integrate_verify_password']))
  117. if (call_user_func($modSettings['integrate_verify_password'], $user_info['username'], $_POST['admin_hash_pass'], true) === true)
  118. $good_password = true;
  119. if ($good_password || $_POST['admin_hash_pass'] == sha1($user_info['passwd'] . $sc))
  120. {
  121. $_SESSION['admin_time'] = time();
  122. return;
  123. }
  124. }
  125. // Posting the password... check it.
  126. if (isset($_POST['admin_pass']))
  127. {
  128. checkSession();
  129. $good_password = false;
  130. if (isset($modSettings['integrate_verify_password']) && function_exists($modSettings['integrate_verify_password']))
  131. if (call_user_func($modSettings['integrate_verify_password'], $user_info['username'], $_POST['admin_pass'], false) === true)
  132. $good_password = true;
  133. // Password correct?
  134. if ($good_password || sha1(strtolower($user_info['username']) . $_POST['admin_pass']) == $user_info['passwd'])
  135. {
  136. $_SESSION['admin_time'] = time();
  137. return;
  138. }
  139. }
  140. // OpenID?
  141. if (!empty($user_settings['openid_uri']))
  142. {
  143. require_once($sourcedir . '/Subs-OpenID.php');
  144. smf_openID_revalidate();
  145. $_SESSION['admin_time'] = time();
  146. return;
  147. }
  148. // Need to type in a password for that, man.
  149. adminLogin();
  150. }
  151. // Require a user who is logged in. (not a guest.)
  152. function is_not_guest($message = '')
  153. {
  154. global $user_info, $txt, $context;
  155. // Luckily, this person isn't a guest.
  156. if (!$user_info['is_guest'])
  157. return;
  158. // People always worry when they see people doing things they aren't actually doing...
  159. $_GET['action'] = '';
  160. $_GET['board'] = '';
  161. $_GET['topic'] = '';
  162. writeLog(true);
  163. // Just die.
  164. if (isset($_REQUEST['xml']))
  165. obExit(false);
  166. // Attempt to detect if they came from dlattach.
  167. if (!WIRELESS && SMF != 'SSI' && empty($context['theme_loaded']))
  168. loadTheme();
  169. // Never redirect to an attachment
  170. if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
  171. $_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
  172. // Load the Login template and language file.
  173. loadLanguage('Login');
  174. // Are we in wireless mode?
  175. if (WIRELESS)
  176. {
  177. $context['login_error'] = $message ? $message : $txt['only_members_can_access'];
  178. $context['sub_template'] = WIRELESS_PROTOCOL . '_login';
  179. }
  180. else
  181. {
  182. loadTemplate('Login');
  183. $context['sub_template'] = 'kick_guest';
  184. $context['robot_no_index'] = true;
  185. }
  186. // Use the kick_guest sub template...
  187. $context['kick_message'] = $message;
  188. $context['page_title'] = $txt['login'];
  189. obExit();
  190. // We should never get to this point, but if we did we wouldn't know the user isn't a guest.
  191. trigger_error('Hacking attempt...', E_USER_ERROR);
  192. }
  193. // Do banning related stuff. (ie. disallow access....)
  194. function is_not_banned($forceCheck = false)
  195. {
  196. global $txt, $modSettings, $context, $user_info;
  197. global $sourcedir, $cookiename, $user_settings, $smcFunc;
  198. // You cannot be banned if you are an admin - doesn't help if you log out.
  199. if ($user_info['is_admin'])
  200. return;
  201. // Only check the ban every so often. (to reduce load.)
  202. if ($forceCheck || !isset($_SESSION['ban']) || empty($modSettings['banLastUpdated']) || ($_SESSION['ban']['last_checked'] < $modSettings['banLastUpdated']) || $_SESSION['ban']['id_member'] != $user_info['id'] || $_SESSION['ban']['ip'] != $user_info['ip'] || $_SESSION['ban']['ip2'] != $user_info['ip2'] || (isset($user_info['email'], $_SESSION['ban']['email']) && $_SESSION['ban']['email'] != $user_info['email']))
  203. {
  204. // Innocent until proven guilty. (but we know you are! :P)
  205. $_SESSION['ban'] = array(
  206. 'last_checked' => time(),
  207. 'id_member' => $user_info['id'],
  208. 'ip' => $user_info['ip'],
  209. 'ip2' => $user_info['ip2'],
  210. 'email' => $user_info['email'],
  211. );
  212. $ban_query = array();
  213. $ban_query_vars = array('current_time' => time());
  214. $flag_is_activated = false;
  215. // Check both IP addresses.
  216. foreach (array('ip', 'ip2') as $ip_number)
  217. {
  218. // Check if we have a valid IP address.
  219. if (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $user_info[$ip_number], $ip_parts) == 1)
  220. {
  221. $ban_query[] = '((' . $ip_parts[1] . ' BETWEEN bi.ip_low1 AND bi.ip_high1)
  222. AND (' . $ip_parts[2] . ' BETWEEN bi.ip_low2 AND bi.ip_high2)
  223. AND (' . $ip_parts[3] . ' BETWEEN bi.ip_low3 AND bi.ip_high3)
  224. AND (' . $ip_parts[4] . ' BETWEEN bi.ip_low4 AND bi.ip_high4))';
  225. // IP was valid, maybe there's also a hostname...
  226. if (empty($modSettings['disableHostnameLookup']))
  227. {
  228. $hostname = host_from_ip($user_info[$ip_number]);
  229. if (strlen($hostname) > 0)
  230. {
  231. $ban_query[] = '({string:hostname} LIKE bi.hostname)';
  232. $ban_query_vars['hostname'] = $hostname;
  233. }
  234. }
  235. }
  236. // We use '255.255.255.255' for 'unknown' since it's not valid anyway.
  237. elseif ($user_info['ip'] == 'unknown')
  238. $ban_query[] = '(bi.ip_low1 = 255 AND bi.ip_high1 = 255
  239. AND bi.ip_low2 = 255 AND bi.ip_high2 = 255
  240. AND bi.ip_low3 = 255 AND bi.ip_high3 = 255
  241. AND bi.ip_low4 = 255 AND bi.ip_high4 = 255)';
  242. }
  243. // Is their email address banned?
  244. if (strlen($user_info['email']) != 0)
  245. {
  246. $ban_query[] = '({string:email} LIKE bi.email_address)';
  247. $ban_query_vars['email'] = $user_info['email'];
  248. }
  249. // How about this user?
  250. if (!$user_info['is_guest'] && !empty($user_info['id']))
  251. {
  252. $ban_query[] = 'bi.id_member = {int:id_member}';
  253. $ban_query_vars['id_member'] = $user_info['id'];
  254. }
  255. // Check the ban, if there's information.
  256. if (!empty($ban_query))
  257. {
  258. $restrictions = array(
  259. 'cannot_access',
  260. 'cannot_login',
  261. 'cannot_post',
  262. 'cannot_register',
  263. );
  264. $request = $smcFunc['db_query']('', '
  265. SELECT bi.id_ban, bi.email_address, bi.id_member, bg.cannot_access, bg.cannot_register,
  266. bg.cannot_post, bg.cannot_login, bg.reason, IFNULL(bg.expire_time, 0) AS expire_time
  267. FROM {db_prefix}ban_items AS bi
  268. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time}))
  269. WHERE
  270. (' . implode(' OR ', $ban_query) . ')',
  271. $ban_query_vars
  272. );
  273. // Store every type of ban that applies to you in your session.
  274. while ($row = $smcFunc['db_fetch_assoc']($request))
  275. {
  276. foreach ($restrictions as $restriction)
  277. if (!empty($row[$restriction]))
  278. {
  279. $_SESSION['ban'][$restriction]['reason'] = $row['reason'];
  280. $_SESSION['ban'][$restriction]['ids'][] = $row['id_ban'];
  281. if (!isset($_SESSION['ban']['expire_time']) || ($_SESSION['ban']['expire_time'] != 0 && ($row['expire_time'] == 0 || $row['expire_time'] > $_SESSION['ban']['expire_time'])))
  282. $_SESSION['ban']['expire_time'] = $row['expire_time'];
  283. if (!$user_info['is_guest'] && $restriction == 'cannot_access' && ($row['id_member'] == $user_info['id'] || $row['email_address'] == $user_info['email']))
  284. $flag_is_activated = true;
  285. }
  286. }
  287. $smcFunc['db_free_result']($request);
  288. }
  289. // Mark the cannot_access and cannot_post bans as being 'hit'.
  290. if (isset($_SESSION['ban']['cannot_access']) || isset($_SESSION['ban']['cannot_post']) || isset($_SESSION['ban']['cannot_login']))
  291. log_ban(array_merge(isset($_SESSION['ban']['cannot_access']) ? $_SESSION['ban']['cannot_access']['ids'] : array(), isset($_SESSION['ban']['cannot_post']) ? $_SESSION['ban']['cannot_post']['ids'] : array(), isset($_SESSION['ban']['cannot_login']) ? $_SESSION['ban']['cannot_login']['ids'] : array()));
  292. // If for whatever reason the is_activated flag seems wrong, do a little work to clear it up.
  293. if ($user_info['id'] && (($user_settings['is_activated'] >= 10 && !$flag_is_activated)
  294. || ($user_settings['is_activated'] < 10 && $flag_is_activated)))
  295. {
  296. require_once($sourcedir . '/ManageBans.php');
  297. updateBanMembers();
  298. }
  299. }
  300. // Hey, I know you! You're ehm...
  301. if (!isset($_SESSION['ban']['cannot_access']) && !empty($_COOKIE[$cookiename . '_']))
  302. {
  303. $bans = explode(',', $_COOKIE[$cookiename . '_']);
  304. foreach ($bans as $key => $value)
  305. $bans[$key] = (int) $value;
  306. $request = $smcFunc['db_query']('', '
  307. SELECT bi.id_ban, bg.reason
  308. FROM {db_prefix}ban_items AS bi
  309. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  310. WHERE bi.id_ban IN ({array_int:ban_list})
  311. AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})
  312. AND bg.cannot_access = {int:cannot_access}
  313. LIMIT ' . count($bans),
  314. array(
  315. 'cannot_access' => 1,
  316. 'ban_list' => $bans,
  317. 'current_time' => time(),
  318. )
  319. );
  320. while ($row = $smcFunc['db_fetch_assoc']($request))
  321. {
  322. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  323. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  324. }
  325. $smcFunc['db_free_result']($request);
  326. // My mistake. Next time better.
  327. if (!isset($_SESSION['ban']['cannot_access']))
  328. {
  329. require_once($sourcedir . '/Subs-Auth.php');
  330. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  331. setcookie($cookiename . '_', '', time() - 3600, $cookie_url[1], $cookie_url[0], 0);
  332. }
  333. }
  334. // If you're fully banned, it's end of the story for you.
  335. if (isset($_SESSION['ban']['cannot_access']))
  336. {
  337. // We don't wanna see you!
  338. if (!$user_info['is_guest'])
  339. $smcFunc['db_query']('', '
  340. DELETE FROM {db_prefix}log_online
  341. WHERE id_member = {int:current_member}',
  342. array(
  343. 'current_member' => $user_info['id'],
  344. )
  345. );
  346. // 'Log' the user out. Can't have any funny business... (save the name!)
  347. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  348. $user_info['name'] = '';
  349. $user_info['username'] = '';
  350. $user_info['is_guest'] = true;
  351. $user_info['is_admin'] = false;
  352. $user_info['permissions'] = array();
  353. $user_info['id'] = 0;
  354. $context['user'] = array(
  355. 'id' => 0,
  356. 'username' => '',
  357. 'name' => $txt['guest_title'],
  358. 'is_guest' => true,
  359. 'is_logged' => false,
  360. 'is_admin' => false,
  361. 'is_mod' => false,
  362. 'can_mod' => false,
  363. 'language' => $user_info['language'],
  364. );
  365. // A goodbye present.
  366. require_once($sourcedir . '/Subs-Auth.php');
  367. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  368. setcookie($cookiename . '_', implode(',', $_SESSION['ban']['cannot_access']['ids']), time() + 3153600, $cookie_url[1], $cookie_url[0], 0);
  369. // Don't scare anyone, now.
  370. $_GET['action'] = '';
  371. $_GET['board'] = '';
  372. $_GET['topic'] = '';
  373. writeLog(true);
  374. // You banned, sucka!
  375. fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_access']['reason']) ? '' : '<br />' . $_SESSION['ban']['cannot_access']['reason']) . '<br />' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']), 'user');
  376. // If we get here, something's gone wrong.... but let's try anyway.
  377. trigger_error('Hacking attempt...', E_USER_ERROR);
  378. }
  379. // You're not allowed to log in but yet you are. Let's fix that.
  380. elseif (isset($_SESSION['ban']['cannot_login']) && !$user_info['is_guest'])
  381. {
  382. // We don't wanna see you!
  383. $smcFunc['db_query']('', '
  384. DELETE FROM {db_prefix}log_online
  385. WHERE id_member = {int:current_member}',
  386. array(
  387. 'current_member' => $user_info['id'],
  388. )
  389. );
  390. // 'Log' the user out. Can't have any funny business... (save the name!)
  391. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  392. $user_info['name'] = '';
  393. $user_info['username'] = '';
  394. $user_info['is_guest'] = true;
  395. $user_info['is_admin'] = false;
  396. $user_info['permissions'] = array();
  397. $user_info['id'] = 0;
  398. $context['user'] = array(
  399. 'id' => 0,
  400. 'username' => '',
  401. 'name' => $txt['guest_title'],
  402. 'is_guest' => true,
  403. 'is_logged' => false,
  404. 'is_admin' => false,
  405. 'is_mod' => false,
  406. 'can_mod' => false,
  407. 'language' => $user_info['language'],
  408. );
  409. // SMF's Wipe 'n Clean(r) erases all traces.
  410. $_GET['action'] = '';
  411. $_GET['board'] = '';
  412. $_GET['topic'] = '';
  413. writeLog(true);
  414. require_once($sourcedir . '/LogInOut.php');
  415. Logout(true, false);
  416. fatal_error(sprintf($txt['your_ban'], $old_name) . (empty($_SESSION['ban']['cannot_login']['reason']) ? '' : '<br />' . $_SESSION['ban']['cannot_login']['reason']) . '<br />' . (!empty($_SESSION['ban']['expire_time']) ? sprintf($txt['your_ban_expires'], timeformat($_SESSION['ban']['expire_time'], false)) : $txt['your_ban_expires_never']) . '<br />' . $txt['ban_continue_browse'], 'user');
  417. }
  418. // Fix up the banning permissions.
  419. if (isset($user_info['permissions']))
  420. banPermissions();
  421. }
  422. // Fix permissions according to ban status.
  423. function banPermissions()
  424. {
  425. global $user_info, $sourcedir, $modSettings, $context;
  426. // Somehow they got here, at least take away all permissions...
  427. if (isset($_SESSION['ban']['cannot_access']))
  428. $user_info['permissions'] = array();
  429. // Okay, well, you can watch, but don't touch a thing.
  430. elseif (isset($_SESSION['ban']['cannot_post']) || (!empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $user_info['warning']))
  431. {
  432. $denied_permissions = array(
  433. 'pm_send',
  434. 'calendar_post', 'calendar_edit_own', 'calendar_edit_any',
  435. 'poll_post',
  436. 'poll_add_own', 'poll_add_any',
  437. 'poll_edit_own', 'poll_edit_any',
  438. 'poll_lock_own', 'poll_lock_any',
  439. 'poll_remove_own', 'poll_remove_any',
  440. 'manage_attachments', 'manage_smileys', 'manage_boards', 'admin_forum', 'manage_permissions',
  441. 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news',
  442. 'profile_identity_any', 'profile_extra_any', 'profile_title_any',
  443. 'post_new', 'post_reply_own', 'post_reply_any',
  444. 'delete_own', 'delete_any', 'delete_replies',
  445. 'make_sticky',
  446. 'merge_any', 'split_any',
  447. 'modify_own', 'modify_any', 'modify_replies',
  448. 'move_any',
  449. 'send_topic',
  450. 'lock_own', 'lock_any',
  451. 'remove_own', 'remove_any',
  452. 'post_unapproved_topics', 'post_unapproved_replies_own', 'post_unapproved_replies_any',
  453. );
  454. $user_info['permissions'] = array_diff($user_info['permissions'], $denied_permissions);
  455. }
  456. // Are they absolutely under moderation?
  457. elseif (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $user_info['warning'])
  458. {
  459. // Work out what permissions should change...
  460. $permission_change = array(
  461. 'post_new' => 'post_unapproved_topics',
  462. 'post_reply_own' => 'post_unapproved_replies_own',
  463. 'post_reply_any' => 'post_unapproved_replies_any',
  464. 'post_attachment' => 'post_unapproved_attachments',
  465. );
  466. foreach ($permission_change as $old => $new)
  467. {
  468. if (!in_array($old, $user_info['permissions']))
  469. unset($permission_change[$old]);
  470. else
  471. $user_info['permissions'][] = $new;
  472. }
  473. $user_info['permissions'] = array_diff($user_info['permissions'], array_keys($permission_change));
  474. }
  475. //!!! Find a better place to call this? Needs to be after permissions loaded!
  476. // Finally, some bits we cache in the session because it saves queries.
  477. if (isset($_SESSION['mc']) && $_SESSION['mc']['time'] > $modSettings['settings_updated'] && $_SESSION['mc']['id'] == $user_info['id'])
  478. $user_info['mod_cache'] = $_SESSION['mc'];
  479. else
  480. {
  481. require_once($sourcedir . '/Subs-Auth.php');
  482. rebuildModCache();
  483. }
  484. // Now that we have the mod cache taken care of lets setup a cache for the number of mod reports still open
  485. if (isset($_SESSION['rc']) && $_SESSION['rc']['time'] > $modSettings['last_mod_report_action'] && $_SESSION['rc']['id'] == $user_info['id'])
  486. $context['open_mod_reports'] = $_SESSION['rc']['reports'];
  487. elseif ($_SESSION['mc']['bq'] != '0=1')
  488. {
  489. require_once($sourcedir . '/ModerationCenter.php');
  490. recountOpenReports();
  491. }
  492. else
  493. $context['open_mod_reports'] = 0;
  494. }
  495. // Log a ban in the database.
  496. function log_ban($ban_ids = array(), $email = null)
  497. {
  498. global $user_info, $smcFunc;
  499. // Don't log web accelerators, it's very confusing...
  500. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  501. return;
  502. $smcFunc['db_insert']('',
  503. '{db_prefix}log_banned',
  504. array('id_member' => 'int', 'ip' => 'string-16', 'email' => 'string', 'log_time' => 'int'),
  505. array($user_info['id'], $user_info['ip'], ($email === null ? ($user_info['is_guest'] ? '' : $user_info['email']) : $email), time()),
  506. array('id_ban_log')
  507. );
  508. // One extra point for these bans.
  509. if (!empty($ban_ids))
  510. $smcFunc['db_query']('', '
  511. UPDATE {db_prefix}ban_items
  512. SET hits = hits + 1
  513. WHERE id_ban IN ({array_int:ban_ids})',
  514. array(
  515. 'ban_ids' => $ban_ids,
  516. )
  517. );
  518. }
  519. // Checks if a given email address might be banned.
  520. function isBannedEmail($email, $restriction, $error)
  521. {
  522. global $txt, $smcFunc;
  523. // Can't ban an empty email
  524. if (empty($email) || trim($email) == '')
  525. return;
  526. // Let's start with the bans based on your IP/hostname/memberID...
  527. $ban_ids = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['ids'] : array();
  528. $ban_reason = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['reason'] : '';
  529. // ...and add to that the email address you're trying to register.
  530. $request = $smcFunc['db_query']('', '
  531. SELECT bi.id_ban, bg.' . $restriction . ', bg.cannot_access, bg.reason
  532. FROM {db_prefix}ban_items AS bi
  533. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  534. WHERE {string:email} LIKE bi.email_address
  535. AND (bg.' . $restriction . ' = {int:cannot_access} OR bg.cannot_access = {int:cannot_access})
  536. AND (bg.expire_time IS NULL OR bg.expire_time >= {int:now})',
  537. array(
  538. 'email' => $email,
  539. 'cannot_access' => 1,
  540. 'now' => time(),
  541. )
  542. );
  543. while ($row = $smcFunc['db_fetch_assoc']($request))
  544. {
  545. if (!empty($row['cannot_access']))
  546. {
  547. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  548. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  549. }
  550. if (!empty($row[$restriction]))
  551. {
  552. $ban_ids[] = $row['id_ban'];
  553. $ban_reason = $row['reason'];
  554. }
  555. }
  556. $smcFunc['db_free_result']($request);
  557. // You're in biiig trouble. Banned for the rest of this session!
  558. if (isset($_SESSION['ban']['cannot_access']))
  559. {
  560. log_ban($_SESSION['ban']['cannot_access']['ids']);
  561. $_SESSION['ban']['last_checked'] = time();
  562. fatal_error(sprintf($txt['your_ban'], $txt['guest_title']) . $_SESSION['ban']['cannot_access']['reason'], false);
  563. }
  564. if (!empty($ban_ids))
  565. {
  566. // Log this ban for future reference.
  567. log_ban($ban_ids, $email);
  568. fatal_error($error . $ban_reason, false);
  569. }
  570. }
  571. // Make sure the user's correct session was passed, and they came from here. (type can be post, get, or request.)
  572. function checkSession($type = 'post', $from_action = '', $is_fatal = true)
  573. {
  574. global $sc, $modSettings, $boardurl;
  575. // Is it in as $_POST['sc']?
  576. if ($type == 'post')
  577. {
  578. $check = isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null);
  579. if ($check !== $sc)
  580. $error = 'session_timeout';
  581. }
  582. // How about $_GET['sesc']?
  583. elseif ($type == 'get')
  584. {
  585. $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : null);
  586. if ($check !== $sc)
  587. $error = 'session_verify_fail';
  588. }
  589. // Or can it be in either?
  590. elseif ($type == 'request')
  591. {
  592. $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : (isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null)));
  593. if ($check !== $sc)
  594. $error = 'session_verify_fail';
  595. }
  596. // Verify that they aren't changing user agents on us - that could be bad.
  597. if ((!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] != $_SERVER['HTTP_USER_AGENT']) && empty($modSettings['disableCheckUA']))
  598. $error = 'session_verify_fail';
  599. // Make sure a page with session check requirement is not being prefetched.
  600. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  601. {
  602. ob_end_clean();
  603. header('HTTP/1.1 403 Forbidden');
  604. die;
  605. }
  606. // Check the referring site - it should be the same server at least!
  607. $referrer = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
  608. if (!empty($referrer['host']))
  609. {
  610. if (strpos($_SERVER['HTTP_HOST'], ':') !== false)
  611. $real_host = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
  612. else
  613. $real_host = $_SERVER['HTTP_HOST'];
  614. $parsed_url = parse_url($boardurl);
  615. // Are global cookies on? If so, let's check them ;).
  616. if (!empty($modSettings['globalCookies']))
  617. {
  618. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  619. $parsed_url['host'] = $parts[1];
  620. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $referrer['host'], $parts) == 1)
  621. $referrer['host'] = $parts[1];
  622. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $real_host, $parts) == 1)
  623. $real_host = $parts[1];
  624. }
  625. // Okay: referrer must either match parsed_url or real_host.
  626. if (isset($parsed_url['host']) && strtolower($referrer['host']) != strtolower($parsed_url['host']) && strtolower($referrer['host']) != strtolower($real_host))
  627. {
  628. $error = 'verify_url_fail';
  629. $log_error = true;
  630. }
  631. }
  632. // Well, first of all, if a from_action is specified you'd better have an old_url.
  633. if (!empty($from_action) && (!isset($_SESSION['old_url']) || preg_match('~[?;&]action=' . $from_action . '([;&]|$)~', $_SESSION['old_url']) == 0))
  634. {
  635. $error = 'verify_url_fail';
  636. $log_error = true;
  637. }
  638. if (strtolower($_SERVER['HTTP_USER_AGENT']) == 'hacker')
  639. fatal_error('Sound the alarm! It\'s a hacker! Close the castle gates!!', false);
  640. // Everything is ok, return an empty string.
  641. if (!isset($error))
  642. return '';
  643. // A session error occurred, show the error.
  644. elseif ($is_fatal)
  645. {
  646. if (isset($_GET['xml']))
  647. {
  648. ob_end_clean();
  649. header('HTTP/1.1 403 Forbidden - Session timeout');
  650. die;
  651. }
  652. else
  653. fatal_lang_error($error, isset($log_error) ? 'user' : false);
  654. }
  655. // A session error occurred, return the error to the calling function.
  656. else
  657. return $error;
  658. // We really should never fall through here, for very important reasons. Let's make sure.
  659. trigger_error('Hacking attempt...', E_USER_ERROR);
  660. }
  661. // Check if a specific confirm parameter was given.
  662. function checkConfirm($action)
  663. {
  664. global $modSettings;
  665. if (isset($_GET['confirm']) && isset($_SESSION['confirm_' . $action]) && md5($_GET['confirm'] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['confirm_' . $action])
  666. return true;
  667. else
  668. {
  669. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed']);
  670. $_SESSION['confirm_' . $action] = md5($token . $_SERVER['HTTP_USER_AGENT']);
  671. return $token;
  672. }
  673. }
  674. // Check whether a form has been submitted twice.
  675. function checkSubmitOnce($action, $is_fatal = true)
  676. {
  677. global $context;
  678. if (!isset($_SESSION['forms']))
  679. $_SESSION['forms'] = array();
  680. // Register a form number and store it in the session stack. (use this on the page that has the form.)
  681. if ($action == 'register')
  682. {
  683. $context['form_sequence_number'] = 0;
  684. while (empty($context['form_sequence_number']) || in_array($context['form_sequence_number'], $_SESSION['forms']))
  685. $context['form_sequence_number'] = mt_rand(1, 16000000);
  686. }
  687. // Check whether the submitted number can be found in the session.
  688. elseif ($action == 'check')
  689. {
  690. if (!isset($_REQUEST['seqnum']))
  691. return true;
  692. elseif (!in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  693. {
  694. $_SESSION['forms'][] = (int) $_REQUEST['seqnum'];
  695. return true;
  696. }
  697. elseif ($is_fatal)
  698. fatal_lang_error('error_form_already_submitted', false);
  699. else
  700. return false;
  701. }
  702. // Don't check, just free the stack number.
  703. elseif ($action == 'free' && isset($_REQUEST['seqnum']) && in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  704. $_SESSION['forms'] = array_diff($_SESSION['forms'], array($_REQUEST['seqnum']));
  705. elseif ($action != 'free')
  706. trigger_error('checkSubmitOnce(): Invalid action \'' . $action . '\'', E_USER_WARNING);
  707. }
  708. // Check the user's permissions.
  709. function allowedTo($permission, $boards = null)
  710. {
  711. global $user_info, $modSettings, $smcFunc;
  712. // You're always allowed to do nothing. (unless you're a working man, MR. LAZY :P!)
  713. if (empty($permission))
  714. return true;
  715. // You're never allowed to do something if your data hasn't been loaded yet!
  716. if (empty($user_info))
  717. return false;
  718. // Administrators are supermen :P.
  719. if ($user_info['is_admin'])
  720. return true;
  721. // Are we checking the _current_ board, or some other boards?
  722. if ($boards === null)
  723. {
  724. // Check if they can do it.
  725. if (!is_array($permission) && in_array($permission, $user_info['permissions']))
  726. return true;
  727. // Search for any of a list of permissions.
  728. elseif (is_array($permission) && count(array_intersect($permission, $user_info['permissions'])) != 0)
  729. return true;
  730. // You aren't allowed, by default.
  731. else
  732. return false;
  733. }
  734. elseif (!is_array($boards))
  735. $boards = array($boards);
  736. $request = $smcFunc['db_query']('', '
  737. SELECT MIN(bp.add_deny) AS add_deny
  738. FROM {db_prefix}boards AS b
  739. INNER JOIN {db_prefix}board_permissions AS bp ON (bp.id_profile = b.id_profile)
  740. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  741. WHERE b.id_board IN ({array_int:board_list})
  742. AND bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  743. AND bp.permission {raw:permission_list}
  744. AND (mods.id_member IS NOT NULL OR bp.id_group != {int:moderator_group})
  745. GROUP BY b.id_board',
  746. array(
  747. 'current_member' => $user_info['id'],
  748. 'board_list' => $boards,
  749. 'group_list' => $user_info['groups'],
  750. 'moderator_group' => 3,
  751. 'permission_list' => (is_array($permission) ? 'IN (\'' . implode('\', \'', $permission) . '\')' : ' = \'' . $permission . '\''),
  752. )
  753. );
  754. // Make sure they can do it on all of the boards.
  755. if ($smcFunc['db_num_rows']($request) != count($boards))
  756. return false;
  757. $result = true;
  758. while ($row = $smcFunc['db_fetch_assoc']($request))
  759. $result &= !empty($row['add_deny']);
  760. $smcFunc['db_free_result']($request);
  761. // If the query returned 1, they can do it... otherwise, they can't.
  762. return $result;
  763. }
  764. // Fatal error if they cannot...
  765. function isAllowedTo($permission, $boards = null)
  766. {
  767. global $user_info, $txt;
  768. static $heavy_permissions = array(
  769. 'admin_forum',
  770. 'manage_attachments',
  771. 'manage_smileys',
  772. 'manage_boards',
  773. 'edit_news',
  774. 'moderate_forum',
  775. 'manage_bans',
  776. 'manage_membergroups',
  777. 'manage_permissions',
  778. );
  779. // Make it an array, even if a string was passed.
  780. $permission = is_array($permission) ? $permission : array($permission);
  781. // Check the permission and return an error...
  782. if (!allowedTo($permission, $boards))
  783. {
  784. // Pick the last array entry as the permission shown as the error.
  785. $error_permission = array_shift($permission);
  786. // If they are a guest, show a login. (because the error might be gone if they do!)
  787. if ($user_info['is_guest'])
  788. {
  789. loadLanguage('Errors');
  790. is_not_guest($txt['cannot_' . $error_permission]);
  791. }
  792. // Clear the action because they aren't really doing that!
  793. $_GET['action'] = '';
  794. $_GET['board'] = '';
  795. $_GET['topic'] = '';
  796. writeLog(true);
  797. fatal_lang_error('cannot_' . $error_permission, false);
  798. // Getting this far is a really big problem, but let's try our best to prevent any cases...
  799. trigger_error('Hacking attempt...', E_USER_ERROR);
  800. }
  801. // If you're doing something on behalf of some "heavy" permissions, validate your session.
  802. // (take out the heavy permissions, and if you can't do anything but those, you need a validated session.)
  803. if (!allowedTo(array_diff($permission, $heavy_permissions), $boards))
  804. validateSession();
  805. }
  806. // Return the boards a user has a certain (board) permission on. (array(0) if all.)
  807. function boardsAllowedTo($permissions, $check_access = true)
  808. {
  809. global $user_info, $modSettings, $smcFunc;
  810. // Administrators are all powerful, sorry.
  811. if ($user_info['is_admin'])
  812. return array(0);
  813. // Arrays are nice, most of the time.
  814. if (!is_array($permissions))
  815. $permissions = array($permissions);
  816. // All groups the user is in except 'moderator'.
  817. $groups = array_diff($user_info['groups'], array(3));
  818. $request = $smcFunc['db_query']('', '
  819. SELECT b.id_board, bp.add_deny
  820. FROM {db_prefix}board_permissions AS bp
  821. INNER JOIN {db_prefix}boards AS b ON (b.id_profile = bp.id_profile)
  822. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  823. WHERE bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  824. AND bp.permission IN ({array_string:permissions})
  825. AND (mods.id_member IS NOT NULL OR bp.id_group != {int:moderator_group})' .
  826. ($check_access ? ' AND {query_see_board}' : ''),
  827. array(
  828. 'current_member' => $user_info['id'],
  829. 'group_list' => $groups,
  830. 'moderator_group' => 3,
  831. 'permissions' => $permissions,
  832. )
  833. );
  834. $boards = array();
  835. $deny_boards = array();
  836. while ($row = $smcFunc['db_fetch_assoc']($request))
  837. {
  838. if (empty($row['add_deny']))
  839. $deny_boards[] = $row['id_board'];
  840. else
  841. $boards[] = $row['id_board'];
  842. }
  843. $smcFunc['db_free_result']($request);
  844. $boards = array_unique(array_values(array_diff($boards, $deny_boards)));
  845. return $boards;
  846. }
  847. function showEmailAddress($userProfile_hideEmail, $userProfile_id)
  848. {
  849. global $modSettings, $user_info;
  850. // Should this users email address be shown?
  851. // If you're guest and the forum is set to hide email for guests: no.
  852. // If the user is post-banned: no.
  853. // If it's your own profile and you've set your address hidden: yes_permission_override.
  854. // If you're a moderator with sufficient permissions: yes_permission_override.
  855. // If the user has set their email address to be hidden: no.
  856. // If the forum is set to show full email addresses: yes.
  857. // Otherwise: no_through_forum.
  858. return (!empty($modSettings['guest_hideContacts']) && $user_info['is_guest']) || isset($_SESSION['ban']['cannot_post']) ? 'no' : ((!$user_info['is_guest'] && $user_info['id'] == $userProfile_id && !$userProfile_hideEmail) || allowedTo('moderate_forum') ? 'yes_permission_override' : ($userProfile_hideEmail ? 'no' : (!empty($modSettings['make_email_viewable']) ? 'yes' : 'no_through_forum')));
  859. }
  860. ?>