Security.php 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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
  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($type = 'admin')
  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. // Validate what type of session check this is.
  94. $types = array();
  95. call_integration_hook('integrate_validateSession', array($types));
  96. $type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';
  97. // If we're using XML give an additional ten minutes grace as an admin can't log on in XML mode.
  98. $refreshTime = isset($_GET['xml']) ? 4200 : 3600;
  99. // Is the security option off? Or are they already logged in?
  100. if (!empty($modSettings['securityDisable' . $type != 'admin' ? '_' . $type : '']) || (!empty($_SESSION[$type . '_time']) && $_SESSION[$type . '_time'] + $refreshTime >= time()))
  101. return;
  102. require_once($sourcedir . '/Subs-Auth.php');
  103. // Hashed password, ahoy!
  104. if (isset($_POST[$type . '_hash_pass']) && strlen($_POST[$type . '_hash_pass']) == 40)
  105. {
  106. checkSession();
  107. $good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST[$type . '_hash_pass'], true)), true);
  108. if ($good_password || $_POST[$type . '_hash_pass'] == sha1($user_info['passwd'] . $sc))
  109. {
  110. $_SESSION[$type . '_time'] = time();
  111. return;
  112. }
  113. }
  114. // Posting the password... check it.
  115. if (isset($_POST[$type. '_pass']))
  116. {
  117. checkSession();
  118. $good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST[$type . '_pass'], false)), true);
  119. // Password correct?
  120. if ($good_password || sha1(strtolower($user_info['username']) . $_POST[$type . '_pass']) == $user_info['passwd'])
  121. {
  122. $_SESSION[$type . '_time'] = time();
  123. return;
  124. }
  125. }
  126. // OpenID?
  127. if (!empty($user_settings['openid_uri']))
  128. {
  129. require_once($sourcedir . '/Subs-OpenID.php');
  130. smf_openID_revalidate();
  131. $_SESSION[$type . '_time'] = time();
  132. return;
  133. }
  134. // Need to type in a password for that, man.
  135. adminLogin($type);
  136. }
  137. // Require a user who is logged in. (not a guest.)
  138. function is_not_guest($message = '')
  139. {
  140. global $user_info, $txt, $context, $scripturl;
  141. // Luckily, this person isn't a guest.
  142. if (!$user_info['is_guest'])
  143. return;
  144. // People always worry when they see people doing things they aren't actually doing...
  145. $_GET['action'] = '';
  146. $_GET['board'] = '';
  147. $_GET['topic'] = '';
  148. writeLog(true);
  149. // Just die.
  150. if (isset($_REQUEST['xml']))
  151. obExit(false);
  152. // Attempt to detect if they came from dlattach.
  153. if (!WIRELESS && SMF != 'SSI' && empty($context['theme_loaded']))
  154. loadTheme();
  155. // Never redirect to an attachment
  156. if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
  157. $_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
  158. // Load the Login template and language file.
  159. loadLanguage('Login');
  160. // Are we in wireless mode?
  161. if (WIRELESS)
  162. {
  163. $context['login_error'] = $message ? $message : $txt['only_members_can_access'];
  164. $context['sub_template'] = WIRELESS_PROTOCOL . '_login';
  165. }
  166. // Apparently we're not in a position to handle this now. Let's go to a safer location for now.
  167. elseif (empty($context['template_layers']))
  168. {
  169. $_SESSION['login_url'] = $scripturl . '?' . $_SERVER['QUERY_STRING'];
  170. redirectexit('action=login');
  171. }
  172. else
  173. {
  174. loadTemplate('Login');
  175. $context['sub_template'] = 'kick_guest';
  176. $context['robot_no_index'] = true;
  177. }
  178. // Use the kick_guest sub template...
  179. $context['kick_message'] = $message;
  180. $context['page_title'] = $txt['login'];
  181. obExit();
  182. // We should never get to this point, but if we did we wouldn't know the user isn't a guest.
  183. trigger_error('Hacking attempt...', E_USER_ERROR);
  184. }
  185. // Do banning related stuff. (ie. disallow access....)
  186. function is_not_banned($forceCheck = false)
  187. {
  188. global $txt, $modSettings, $context, $user_info;
  189. global $sourcedir, $cookiename, $user_settings, $smcFunc;
  190. // You cannot be banned if you are an admin - doesn't help if you log out.
  191. if ($user_info['is_admin'])
  192. return;
  193. // Only check the ban every so often. (to reduce load.)
  194. 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']))
  195. {
  196. // Innocent until proven guilty. (but we know you are! :P)
  197. $_SESSION['ban'] = array(
  198. 'last_checked' => time(),
  199. 'id_member' => $user_info['id'],
  200. 'ip' => $user_info['ip'],
  201. 'ip2' => $user_info['ip2'],
  202. 'email' => $user_info['email'],
  203. );
  204. $ban_query = array();
  205. $ban_query_vars = array('current_time' => time());
  206. $flag_is_activated = false;
  207. // Check both IP addresses.
  208. foreach (array('ip', 'ip2') as $ip_number)
  209. {
  210. // Check if we have a valid IP address.
  211. if (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $user_info[$ip_number], $ip_parts) == 1)
  212. {
  213. $ban_query[] = '((' . $ip_parts[1] . ' BETWEEN bi.ip_low1 AND bi.ip_high1)
  214. AND (' . $ip_parts[2] . ' BETWEEN bi.ip_low2 AND bi.ip_high2)
  215. AND (' . $ip_parts[3] . ' BETWEEN bi.ip_low3 AND bi.ip_high3)
  216. AND (' . $ip_parts[4] . ' BETWEEN bi.ip_low4 AND bi.ip_high4))';
  217. // IP was valid, maybe there's also a hostname...
  218. if (empty($modSettings['disableHostnameLookup']))
  219. {
  220. $hostname = host_from_ip($user_info[$ip_number]);
  221. if (strlen($hostname) > 0)
  222. {
  223. $ban_query[] = '({string:hostname} LIKE bi.hostname)';
  224. $ban_query_vars['hostname'] = $hostname;
  225. }
  226. }
  227. }
  228. // We use '255.255.255.255' for 'unknown' since it's not valid anyway.
  229. elseif ($user_info['ip'] == 'unknown')
  230. $ban_query[] = '(bi.ip_low1 = 255 AND bi.ip_high1 = 255
  231. AND bi.ip_low2 = 255 AND bi.ip_high2 = 255
  232. AND bi.ip_low3 = 255 AND bi.ip_high3 = 255
  233. AND bi.ip_low4 = 255 AND bi.ip_high4 = 255)';
  234. }
  235. // Is their email address banned?
  236. if (strlen($user_info['email']) != 0)
  237. {
  238. $ban_query[] = '({string:email} LIKE bi.email_address)';
  239. $ban_query_vars['email'] = $user_info['email'];
  240. }
  241. // How about this user?
  242. if (!$user_info['is_guest'] && !empty($user_info['id']))
  243. {
  244. $ban_query[] = 'bi.id_member = {int:id_member}';
  245. $ban_query_vars['id_member'] = $user_info['id'];
  246. }
  247. // Check the ban, if there's information.
  248. if (!empty($ban_query))
  249. {
  250. $restrictions = array(
  251. 'cannot_access',
  252. 'cannot_login',
  253. 'cannot_post',
  254. 'cannot_register',
  255. );
  256. $request = $smcFunc['db_query']('', '
  257. SELECT bi.id_ban, bi.email_address, bi.id_member, bg.cannot_access, bg.cannot_register,
  258. bg.cannot_post, bg.cannot_login, bg.reason, IFNULL(bg.expire_time, 0) AS expire_time
  259. FROM {db_prefix}ban_items AS bi
  260. 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}))
  261. WHERE
  262. (' . implode(' OR ', $ban_query) . ')',
  263. $ban_query_vars
  264. );
  265. // Store every type of ban that applies to you in your session.
  266. while ($row = $smcFunc['db_fetch_assoc']($request))
  267. {
  268. foreach ($restrictions as $restriction)
  269. if (!empty($row[$restriction]))
  270. {
  271. $_SESSION['ban'][$restriction]['reason'] = $row['reason'];
  272. $_SESSION['ban'][$restriction]['ids'][] = $row['id_ban'];
  273. if (!isset($_SESSION['ban']['expire_time']) || ($_SESSION['ban']['expire_time'] != 0 && ($row['expire_time'] == 0 || $row['expire_time'] > $_SESSION['ban']['expire_time'])))
  274. $_SESSION['ban']['expire_time'] = $row['expire_time'];
  275. if (!$user_info['is_guest'] && $restriction == 'cannot_access' && ($row['id_member'] == $user_info['id'] || $row['email_address'] == $user_info['email']))
  276. $flag_is_activated = true;
  277. }
  278. }
  279. $smcFunc['db_free_result']($request);
  280. }
  281. // Mark the cannot_access and cannot_post bans as being 'hit'.
  282. if (isset($_SESSION['ban']['cannot_access']) || isset($_SESSION['ban']['cannot_post']) || isset($_SESSION['ban']['cannot_login']))
  283. 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()));
  284. // If for whatever reason the is_activated flag seems wrong, do a little work to clear it up.
  285. if ($user_info['id'] && (($user_settings['is_activated'] >= 10 && !$flag_is_activated)
  286. || ($user_settings['is_activated'] < 10 && $flag_is_activated)))
  287. {
  288. require_once($sourcedir . '/ManageBans.php');
  289. updateBanMembers();
  290. }
  291. }
  292. // Hey, I know you! You're ehm...
  293. if (!isset($_SESSION['ban']['cannot_access']) && !empty($_COOKIE[$cookiename . '_']))
  294. {
  295. $bans = explode(',', $_COOKIE[$cookiename . '_']);
  296. foreach ($bans as $key => $value)
  297. $bans[$key] = (int) $value;
  298. $request = $smcFunc['db_query']('', '
  299. SELECT bi.id_ban, bg.reason
  300. FROM {db_prefix}ban_items AS bi
  301. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  302. WHERE bi.id_ban IN ({array_int:ban_list})
  303. AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})
  304. AND bg.cannot_access = {int:cannot_access}
  305. LIMIT ' . count($bans),
  306. array(
  307. 'cannot_access' => 1,
  308. 'ban_list' => $bans,
  309. 'current_time' => time(),
  310. )
  311. );
  312. while ($row = $smcFunc['db_fetch_assoc']($request))
  313. {
  314. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  315. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  316. }
  317. $smcFunc['db_free_result']($request);
  318. // My mistake. Next time better.
  319. if (!isset($_SESSION['ban']['cannot_access']))
  320. {
  321. require_once($sourcedir . '/Subs-Auth.php');
  322. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  323. setcookie($cookiename . '_', '', time() - 3600, $cookie_url[1], $cookie_url[0], 0);
  324. }
  325. }
  326. // If you're fully banned, it's end of the story for you.
  327. if (isset($_SESSION['ban']['cannot_access']))
  328. {
  329. // We don't wanna see you!
  330. if (!$user_info['is_guest'])
  331. $smcFunc['db_query']('', '
  332. DELETE FROM {db_prefix}log_online
  333. WHERE id_member = {int:current_member}',
  334. array(
  335. 'current_member' => $user_info['id'],
  336. )
  337. );
  338. // 'Log' the user out. Can't have any funny business... (save the name!)
  339. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  340. $user_info['name'] = '';
  341. $user_info['username'] = '';
  342. $user_info['is_guest'] = true;
  343. $user_info['is_admin'] = false;
  344. $user_info['permissions'] = array();
  345. $user_info['id'] = 0;
  346. $context['user'] = array(
  347. 'id' => 0,
  348. 'username' => '',
  349. 'name' => $txt['guest_title'],
  350. 'is_guest' => true,
  351. 'is_logged' => false,
  352. 'is_admin' => false,
  353. 'is_mod' => false,
  354. 'can_mod' => false,
  355. 'language' => $user_info['language'],
  356. );
  357. // A goodbye present.
  358. require_once($sourcedir . '/Subs-Auth.php');
  359. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  360. setcookie($cookiename . '_', implode(',', $_SESSION['ban']['cannot_access']['ids']), time() + 3153600, $cookie_url[1], $cookie_url[0], 0);
  361. // Don't scare anyone, now.
  362. $_GET['action'] = '';
  363. $_GET['board'] = '';
  364. $_GET['topic'] = '';
  365. writeLog(true);
  366. // You banned, sucka!
  367. 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');
  368. // If we get here, something's gone wrong.... but let's try anyway.
  369. trigger_error('Hacking attempt...', E_USER_ERROR);
  370. }
  371. // You're not allowed to log in but yet you are. Let's fix that.
  372. elseif (isset($_SESSION['ban']['cannot_login']) && !$user_info['is_guest'])
  373. {
  374. // We don't wanna see you!
  375. $smcFunc['db_query']('', '
  376. DELETE FROM {db_prefix}log_online
  377. WHERE id_member = {int:current_member}',
  378. array(
  379. 'current_member' => $user_info['id'],
  380. )
  381. );
  382. // 'Log' the user out. Can't have any funny business... (save the name!)
  383. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  384. $user_info['name'] = '';
  385. $user_info['username'] = '';
  386. $user_info['is_guest'] = true;
  387. $user_info['is_admin'] = false;
  388. $user_info['permissions'] = array();
  389. $user_info['id'] = 0;
  390. $context['user'] = array(
  391. 'id' => 0,
  392. 'username' => '',
  393. 'name' => $txt['guest_title'],
  394. 'is_guest' => true,
  395. 'is_logged' => false,
  396. 'is_admin' => false,
  397. 'is_mod' => false,
  398. 'can_mod' => false,
  399. 'language' => $user_info['language'],
  400. );
  401. // SMF's Wipe 'n Clean(r) erases all traces.
  402. $_GET['action'] = '';
  403. $_GET['board'] = '';
  404. $_GET['topic'] = '';
  405. writeLog(true);
  406. require_once($sourcedir . '/LogInOut.php');
  407. Logout(true, false);
  408. 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');
  409. }
  410. // Fix up the banning permissions.
  411. if (isset($user_info['permissions']))
  412. banPermissions();
  413. }
  414. // Fix permissions according to ban status.
  415. function banPermissions()
  416. {
  417. global $user_info, $sourcedir, $modSettings, $context;
  418. // Somehow they got here, at least take away all permissions...
  419. if (isset($_SESSION['ban']['cannot_access']))
  420. $user_info['permissions'] = array();
  421. // Okay, well, you can watch, but don't touch a thing.
  422. elseif (isset($_SESSION['ban']['cannot_post']) || (!empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $user_info['warning']))
  423. {
  424. $denied_permissions = array(
  425. 'pm_send',
  426. 'calendar_post', 'calendar_edit_own', 'calendar_edit_any',
  427. 'poll_post',
  428. 'poll_add_own', 'poll_add_any',
  429. 'poll_edit_own', 'poll_edit_any',
  430. 'poll_lock_own', 'poll_lock_any',
  431. 'poll_remove_own', 'poll_remove_any',
  432. 'manage_attachments', 'manage_smileys', 'manage_boards', 'admin_forum', 'manage_permissions',
  433. 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news',
  434. 'profile_identity_any', 'profile_extra_any', 'profile_title_any',
  435. 'post_new', 'post_reply_own', 'post_reply_any',
  436. 'delete_own', 'delete_any', 'delete_replies',
  437. 'make_sticky',
  438. 'merge_any', 'split_any',
  439. 'modify_own', 'modify_any', 'modify_replies',
  440. 'move_any',
  441. 'send_topic',
  442. 'lock_own', 'lock_any',
  443. 'remove_own', 'remove_any',
  444. 'post_unapproved_topics', 'post_unapproved_replies_own', 'post_unapproved_replies_any',
  445. );
  446. $user_info['permissions'] = array_diff($user_info['permissions'], $denied_permissions);
  447. }
  448. // Are they absolutely under moderation?
  449. elseif (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $user_info['warning'])
  450. {
  451. // Work out what permissions should change...
  452. $permission_change = array(
  453. 'post_new' => 'post_unapproved_topics',
  454. 'post_reply_own' => 'post_unapproved_replies_own',
  455. 'post_reply_any' => 'post_unapproved_replies_any',
  456. 'post_attachment' => 'post_unapproved_attachments',
  457. );
  458. foreach ($permission_change as $old => $new)
  459. {
  460. if (!in_array($old, $user_info['permissions']))
  461. unset($permission_change[$old]);
  462. else
  463. $user_info['permissions'][] = $new;
  464. }
  465. $user_info['permissions'] = array_diff($user_info['permissions'], array_keys($permission_change));
  466. }
  467. // @todo Find a better place to call this? Needs to be after permissions loaded!
  468. // Finally, some bits we cache in the session because it saves queries.
  469. if (isset($_SESSION['mc']) && $_SESSION['mc']['time'] > $modSettings['settings_updated'] && $_SESSION['mc']['id'] == $user_info['id'])
  470. $user_info['mod_cache'] = $_SESSION['mc'];
  471. else
  472. {
  473. require_once($sourcedir . '/Subs-Auth.php');
  474. rebuildModCache();
  475. }
  476. // Now that we have the mod cache taken care of lets setup a cache for the number of mod reports still open
  477. if (isset($_SESSION['rc']) && $_SESSION['rc']['time'] > $modSettings['last_mod_report_action'] && $_SESSION['rc']['id'] == $user_info['id'])
  478. $context['open_mod_reports'] = $_SESSION['rc']['reports'];
  479. elseif ($_SESSION['mc']['bq'] != '0=1')
  480. {
  481. require_once($sourcedir . '/ModerationCenter.php');
  482. recountOpenReports();
  483. }
  484. else
  485. $context['open_mod_reports'] = 0;
  486. }
  487. // Log a ban in the database.
  488. function log_ban($ban_ids = array(), $email = null)
  489. {
  490. global $user_info, $smcFunc;
  491. // Don't log web accelerators, it's very confusing...
  492. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  493. return;
  494. $smcFunc['db_insert']('',
  495. '{db_prefix}log_banned',
  496. array('id_member' => 'int', 'ip' => 'string-16', 'email' => 'string', 'log_time' => 'int'),
  497. array($user_info['id'], $user_info['ip'], ($email === null ? ($user_info['is_guest'] ? '' : $user_info['email']) : $email), time()),
  498. array('id_ban_log')
  499. );
  500. // One extra point for these bans.
  501. if (!empty($ban_ids))
  502. $smcFunc['db_query']('', '
  503. UPDATE {db_prefix}ban_items
  504. SET hits = hits + 1
  505. WHERE id_ban IN ({array_int:ban_ids})',
  506. array(
  507. 'ban_ids' => $ban_ids,
  508. )
  509. );
  510. }
  511. // Checks if a given email address might be banned.
  512. function isBannedEmail($email, $restriction, $error)
  513. {
  514. global $txt, $smcFunc;
  515. // Can't ban an empty email
  516. if (empty($email) || trim($email) == '')
  517. return;
  518. // Let's start with the bans based on your IP/hostname/memberID...
  519. $ban_ids = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['ids'] : array();
  520. $ban_reason = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['reason'] : '';
  521. // ...and add to that the email address you're trying to register.
  522. $request = $smcFunc['db_query']('', '
  523. SELECT bi.id_ban, bg.' . $restriction . ', bg.cannot_access, bg.reason
  524. FROM {db_prefix}ban_items AS bi
  525. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  526. WHERE {string:email} LIKE bi.email_address
  527. AND (bg.' . $restriction . ' = {int:cannot_access} OR bg.cannot_access = {int:cannot_access})
  528. AND (bg.expire_time IS NULL OR bg.expire_time >= {int:now})',
  529. array(
  530. 'email' => $email,
  531. 'cannot_access' => 1,
  532. 'now' => time(),
  533. )
  534. );
  535. while ($row = $smcFunc['db_fetch_assoc']($request))
  536. {
  537. if (!empty($row['cannot_access']))
  538. {
  539. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  540. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  541. }
  542. if (!empty($row[$restriction]))
  543. {
  544. $ban_ids[] = $row['id_ban'];
  545. $ban_reason = $row['reason'];
  546. }
  547. }
  548. $smcFunc['db_free_result']($request);
  549. // You're in biiig trouble. Banned for the rest of this session!
  550. if (isset($_SESSION['ban']['cannot_access']))
  551. {
  552. log_ban($_SESSION['ban']['cannot_access']['ids']);
  553. $_SESSION['ban']['last_checked'] = time();
  554. fatal_error(sprintf($txt['your_ban'], $txt['guest_title']) . $_SESSION['ban']['cannot_access']['reason'], false);
  555. }
  556. if (!empty($ban_ids))
  557. {
  558. // Log this ban for future reference.
  559. log_ban($ban_ids, $email);
  560. fatal_error($error . $ban_reason, false);
  561. }
  562. }
  563. // Make sure the user's correct session was passed, and they came from here. (type can be post, get, or request.)
  564. function checkSession($type = 'post', $from_action = '', $is_fatal = true)
  565. {
  566. global $sc, $modSettings, $boardurl;
  567. // Is it in as $_POST['sc']?
  568. if ($type == 'post')
  569. {
  570. $check = isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null);
  571. if ($check !== $sc)
  572. $error = 'session_timeout';
  573. }
  574. // How about $_GET['sesc']?
  575. elseif ($type == 'get')
  576. {
  577. $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : null);
  578. if ($check !== $sc)
  579. $error = 'session_verify_fail';
  580. }
  581. // Or can it be in either?
  582. elseif ($type == 'request')
  583. {
  584. $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)));
  585. if ($check !== $sc)
  586. $error = 'session_verify_fail';
  587. }
  588. // Verify that they aren't changing user agents on us - that could be bad.
  589. if ((!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] != $_SERVER['HTTP_USER_AGENT']) && empty($modSettings['disableCheckUA']))
  590. $error = 'session_verify_fail';
  591. // Make sure a page with session check requirement is not being prefetched.
  592. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  593. {
  594. ob_end_clean();
  595. header('HTTP/1.1 403 Forbidden');
  596. die;
  597. }
  598. // Check the referring site - it should be the same server at least!
  599. $referrer = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
  600. if (!empty($referrer['host']))
  601. {
  602. if (strpos($_SERVER['HTTP_HOST'], ':') !== false)
  603. $real_host = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
  604. else
  605. $real_host = $_SERVER['HTTP_HOST'];
  606. $parsed_url = parse_url($boardurl);
  607. // Are global cookies on? If so, let's check them ;).
  608. if (!empty($modSettings['globalCookies']))
  609. {
  610. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  611. $parsed_url['host'] = $parts[1];
  612. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $referrer['host'], $parts) == 1)
  613. $referrer['host'] = $parts[1];
  614. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $real_host, $parts) == 1)
  615. $real_host = $parts[1];
  616. }
  617. // Okay: referrer must either match parsed_url or real_host.
  618. if (isset($parsed_url['host']) && strtolower($referrer['host']) != strtolower($parsed_url['host']) && strtolower($referrer['host']) != strtolower($real_host))
  619. {
  620. $error = 'verify_url_fail';
  621. $log_error = true;
  622. }
  623. }
  624. // Well, first of all, if a from_action is specified you'd better have an old_url.
  625. if (!empty($from_action) && (!isset($_SESSION['old_url']) || preg_match('~[?;&]action=' . $from_action . '([;&]|$)~', $_SESSION['old_url']) == 0))
  626. {
  627. $error = 'verify_url_fail';
  628. $log_error = true;
  629. }
  630. if (strtolower($_SERVER['HTTP_USER_AGENT']) == 'hacker')
  631. fatal_error('Sound the alarm! It\'s a hacker! Close the castle gates!!', false);
  632. // Everything is ok, return an empty string.
  633. if (!isset($error))
  634. return '';
  635. // A session error occurred, show the error.
  636. elseif ($is_fatal)
  637. {
  638. if (isset($_GET['xml']))
  639. {
  640. ob_end_clean();
  641. header('HTTP/1.1 403 Forbidden - Session timeout');
  642. die;
  643. }
  644. else
  645. fatal_lang_error($error, isset($log_error) ? 'user' : false);
  646. }
  647. // A session error occurred, return the error to the calling function.
  648. else
  649. return $error;
  650. // We really should never fall through here, for very important reasons. Let's make sure.
  651. trigger_error('Hacking attempt...', E_USER_ERROR);
  652. }
  653. // Check if a specific confirm parameter was given.
  654. function checkConfirm($action)
  655. {
  656. global $modSettings;
  657. if (isset($_GET['confirm']) && isset($_SESSION['confirm_' . $action]) && md5($_GET['confirm'] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['confirm_' . $action])
  658. return true;
  659. else
  660. {
  661. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed']);
  662. $_SESSION['confirm_' . $action] = md5($token . $_SERVER['HTTP_USER_AGENT']);
  663. return $token;
  664. }
  665. }
  666. // Lets give you a token of our appreciation.
  667. function createToken($action, $type = 'post')
  668. {
  669. global $modSettings, $context;
  670. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed'] . $type);
  671. $token_var = substr(preg_replace('~^\d+~', '', md5(mt_rand() . (string) microtime() . mt_rand())), 0, rand(7, 12));
  672. $_SESSION['token'][$type . '-' . $action] = array($token_var, md5($token . $_SERVER['HTTP_USER_AGENT']), time(), $token);
  673. $context[$action . '_token'] = $token;
  674. $context[$action . '_token_var'] = $token_var;
  675. return array($token_var, $token);
  676. }
  677. // Only patrons with valid tokens can ride this ride.
  678. function validateToken($action, $type = 'post', $reset = true)
  679. {
  680. global $modSettings;
  681. $type = $type == 'get' || $type == 'request' ? $type : 'post';
  682. // This nasty piece of code validates a token.
  683. /*
  684. 1. The token exists in session.
  685. 2. The {$type} variable should exist.
  686. 3. We concat the variable we received with the user agent
  687. 4. Match that result against what is in the session.
  688. 5. If it matchs, success, otherwise we fallout.
  689. */
  690. if (isset($_SESSION['token'][$type . '-' . $action], $GLOBALS['_' . strtoupper($type)][$_SESSION['token'][$type . '-' . $action][0]]) && md5($GLOBALS['_' . strtoupper($type)][$_SESSION['token'][$type . '-' . $action][0]] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['token'][$type . '-' . $action][1])
  691. {
  692. // Invalidate this token now.
  693. unset($_SESSION['token'][$type . '-' . $action]);
  694. return true;
  695. }
  696. // Patrons with invalid tokens get the boot.
  697. if ($reset)
  698. {
  699. // Might as well do some cleanup on this.
  700. cleanTokens();
  701. // I'm back baby.
  702. createToken($action, $type);
  703. fatal_lang_error('token_verify_fail', false);
  704. }
  705. // Remove this token as its useless
  706. else
  707. unset($_SESSION['token'][$type . '-' . $action]);
  708. // Randomly check if we should remove some older tokens.
  709. if (mt_rand(0, 138) == 23)
  710. cleanTokens();
  711. return false;
  712. }
  713. // Clean up a little.
  714. function cleanTokens($complete = false)
  715. {
  716. // We appreciate cleaning up after yourselves.
  717. if (!isset($_SESSION['token']))
  718. return;
  719. // Clean up tokens, trying to give enough time still.
  720. foreach ($_SESSION['token'] as $key => $data)
  721. if ($data[2] + 10800 < time() || $complete)
  722. unset($_SESSION['token'][$key]);
  723. }
  724. // Check whether a form has been submitted twice.
  725. function checkSubmitOnce($action, $is_fatal = true)
  726. {
  727. global $context;
  728. if (!isset($_SESSION['forms']))
  729. $_SESSION['forms'] = array();
  730. // Register a form number and store it in the session stack. (use this on the page that has the form.)
  731. if ($action == 'register')
  732. {
  733. $context['form_sequence_number'] = 0;
  734. while (empty($context['form_sequence_number']) || in_array($context['form_sequence_number'], $_SESSION['forms']))
  735. $context['form_sequence_number'] = mt_rand(1, 16000000);
  736. }
  737. // Check whether the submitted number can be found in the session.
  738. elseif ($action == 'check')
  739. {
  740. if (!isset($_REQUEST['seqnum']))
  741. return true;
  742. elseif (!in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  743. {
  744. $_SESSION['forms'][] = (int) $_REQUEST['seqnum'];
  745. return true;
  746. }
  747. elseif ($is_fatal)
  748. fatal_lang_error('error_form_already_submitted', false);
  749. else
  750. return false;
  751. }
  752. // Don't check, just free the stack number.
  753. elseif ($action == 'free' && isset($_REQUEST['seqnum']) && in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  754. $_SESSION['forms'] = array_diff($_SESSION['forms'], array($_REQUEST['seqnum']));
  755. elseif ($action != 'free')
  756. trigger_error('checkSubmitOnce(): Invalid action \'' . $action . '\'', E_USER_WARNING);
  757. }
  758. // Check the user's permissions.
  759. function allowedTo($permission, $boards = null)
  760. {
  761. global $user_info, $modSettings, $smcFunc;
  762. // You're always allowed to do nothing. (unless you're a working man, MR. LAZY :P!)
  763. if (empty($permission))
  764. return true;
  765. // You're never allowed to do something if your data hasn't been loaded yet!
  766. if (empty($user_info))
  767. return false;
  768. // Administrators are supermen :P.
  769. if ($user_info['is_admin'])
  770. return true;
  771. // Are we checking the _current_ board, or some other boards?
  772. if ($boards === null)
  773. {
  774. // Check if they can do it.
  775. if (!is_array($permission) && in_array($permission, $user_info['permissions']))
  776. return true;
  777. // Search for any of a list of permissions.
  778. elseif (is_array($permission) && count(array_intersect($permission, $user_info['permissions'])) != 0)
  779. return true;
  780. // You aren't allowed, by default.
  781. else
  782. return false;
  783. }
  784. elseif (!is_array($boards))
  785. $boards = array($boards);
  786. $request = $smcFunc['db_query']('', '
  787. SELECT MIN(bp.add_deny) AS add_deny
  788. FROM {db_prefix}boards AS b
  789. INNER JOIN {db_prefix}board_permissions AS bp ON (bp.id_profile = b.id_profile)
  790. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  791. WHERE b.id_board IN ({array_int:board_list})
  792. AND bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  793. AND bp.permission {raw:permission_list}
  794. AND (mods.id_member IS NOT NULL OR bp.id_group != {int:moderator_group})
  795. GROUP BY b.id_board',
  796. array(
  797. 'current_member' => $user_info['id'],
  798. 'board_list' => $boards,
  799. 'group_list' => $user_info['groups'],
  800. 'moderator_group' => 3,
  801. 'permission_list' => (is_array($permission) ? 'IN (\'' . implode('\', \'', $permission) . '\')' : ' = \'' . $permission . '\''),
  802. )
  803. );
  804. // Make sure they can do it on all of the boards.
  805. if ($smcFunc['db_num_rows']($request) != count($boards))
  806. return false;
  807. $result = true;
  808. while ($row = $smcFunc['db_fetch_assoc']($request))
  809. $result &= !empty($row['add_deny']);
  810. $smcFunc['db_free_result']($request);
  811. // If the query returned 1, they can do it... otherwise, they can't.
  812. return $result;
  813. }
  814. // Fatal error if they cannot...
  815. function isAllowedTo($permission, $boards = null)
  816. {
  817. global $user_info, $txt;
  818. static $heavy_permissions = array(
  819. 'admin_forum',
  820. 'manage_attachments',
  821. 'manage_smileys',
  822. 'manage_boards',
  823. 'edit_news',
  824. 'moderate_forum',
  825. 'manage_bans',
  826. 'manage_membergroups',
  827. 'manage_permissions',
  828. );
  829. // Make it an array, even if a string was passed.
  830. $permission = is_array($permission) ? $permission : array($permission);
  831. // Check the permission and return an error...
  832. if (!allowedTo($permission, $boards))
  833. {
  834. // Pick the last array entry as the permission shown as the error.
  835. $error_permission = array_shift($permission);
  836. // If they are a guest, show a login. (because the error might be gone if they do!)
  837. if ($user_info['is_guest'])
  838. {
  839. loadLanguage('Errors');
  840. is_not_guest($txt['cannot_' . $error_permission]);
  841. }
  842. // Clear the action because they aren't really doing that!
  843. $_GET['action'] = '';
  844. $_GET['board'] = '';
  845. $_GET['topic'] = '';
  846. writeLog(true);
  847. fatal_lang_error('cannot_' . $error_permission, false);
  848. // Getting this far is a really big problem, but let's try our best to prevent any cases...
  849. trigger_error('Hacking attempt...', E_USER_ERROR);
  850. }
  851. // If you're doing something on behalf of some "heavy" permissions, validate your session.
  852. // (take out the heavy permissions, and if you can't do anything but those, you need a validated session.)
  853. if (!allowedTo(array_diff($permission, $heavy_permissions), $boards))
  854. validateSession();
  855. }
  856. // Return the boards a user has a certain (board) permission on. (array(0) if all.)
  857. function boardsAllowedTo($permissions, $check_access = true)
  858. {
  859. global $user_info, $modSettings, $smcFunc;
  860. // Administrators are all powerful, sorry.
  861. if ($user_info['is_admin'])
  862. return array(0);
  863. // Arrays are nice, most of the time.
  864. if (!is_array($permissions))
  865. $permissions = array($permissions);
  866. // All groups the user is in except 'moderator'.
  867. $groups = array_diff($user_info['groups'], array(3));
  868. $request = $smcFunc['db_query']('', '
  869. SELECT b.id_board, bp.add_deny
  870. FROM {db_prefix}board_permissions AS bp
  871. INNER JOIN {db_prefix}boards AS b ON (b.id_profile = bp.id_profile)
  872. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  873. WHERE bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  874. AND bp.permission IN ({array_string:permissions})
  875. AND (mods.id_member IS NOT NULL OR bp.id_group != {int:moderator_group})' .
  876. ($check_access ? ' AND {query_see_board}' : ''),
  877. array(
  878. 'current_member' => $user_info['id'],
  879. 'group_list' => $groups,
  880. 'moderator_group' => 3,
  881. 'permissions' => $permissions,
  882. )
  883. );
  884. $boards = array();
  885. $deny_boards = array();
  886. while ($row = $smcFunc['db_fetch_assoc']($request))
  887. {
  888. if (empty($row['add_deny']))
  889. $deny_boards[] = $row['id_board'];
  890. else
  891. $boards[] = $row['id_board'];
  892. }
  893. $smcFunc['db_free_result']($request);
  894. $boards = array_unique(array_values(array_diff($boards, $deny_boards)));
  895. return $boards;
  896. }
  897. function showEmailAddress($userProfile_hideEmail, $userProfile_id)
  898. {
  899. global $modSettings, $user_info;
  900. // Should this users email address be shown?
  901. // If you're guest and the forum is set to hide email for guests: no.
  902. // If the user is post-banned: no.
  903. // If it's your own profile and you've set your address hidden: yes_permission_override.
  904. // If you're a moderator with sufficient permissions: yes_permission_override.
  905. // If the user has set their email address to be hidden: no.
  906. // If the forum is set to show full email addresses: yes.
  907. // Otherwise: no_through_forum.
  908. 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')));
  909. }
  910. /**
  911. * This function attempts to protect from spammed messages and the like.
  912. * The time taken depends on error_type - generally uses the modSetting.
  913. *
  914. * @param string $error_type, used also as a $txt index. (not an actual string.)
  915. * @return boolean
  916. */
  917. function spamProtection($error_type)
  918. {
  919. global $modSettings, $txt, $user_info, $smcFunc;
  920. // Certain types take less/more time.
  921. $timeOverrides = array(
  922. 'login' => 2,
  923. 'register' => 2,
  924. 'sendtopc' => $modSettings['spamWaitTime'] * 4,
  925. 'sendmail' => $modSettings['spamWaitTime'] * 5,
  926. 'reporttm' => $modSettings['spamWaitTime'] * 4,
  927. 'search' => !empty($modSettings['search_floodcontrol_time']) ? $modSettings['search_floodcontrol_time'] : 1,
  928. );
  929. // Moderators are free...
  930. if (!allowedTo('moderate_board'))
  931. $timeLimit = isset($timeOverrides[$error_type]) ? $timeOverrides[$error_type] : $modSettings['spamWaitTime'];
  932. else
  933. $timeLimit = 2;
  934. // Delete old entries...
  935. $smcFunc['db_query']('', '
  936. DELETE FROM {db_prefix}log_floodcontrol
  937. WHERE log_time < {int:log_time}
  938. AND log_type = {string:log_type}',
  939. array(
  940. 'log_time' => time() - $timeLimit,
  941. 'log_type' => $error_type,
  942. )
  943. );
  944. // Add a new entry, deleting the old if necessary.
  945. $smcFunc['db_insert']('replace',
  946. '{db_prefix}log_floodcontrol',
  947. array('ip' => 'string-16', 'log_time' => 'int', 'log_type' => 'string'),
  948. array($user_info['ip'], time(), $error_type),
  949. array('ip', 'log_type')
  950. );
  951. // If affected is 0 or 2, it was there already.
  952. if ($smcFunc['db_affected_rows']() != 1)
  953. {
  954. // Spammer! You only have to wait a *few* seconds!
  955. fatal_lang_error($error_type . 'WaitTime_broken', false, array($timeLimit));
  956. return true;
  957. }
  958. // They haven't posted within the limit.
  959. return false;
  960. }
  961. ?>