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

/php/Sources/Security.php

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