Security.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. <?php
  2. /**
  3. * This file has the very important job of ensuring forum security.
  4. * This task includes banning and permissions, namely.
  5. *
  6. * Simple Machines Forum (SMF)
  7. *
  8. * @package SMF
  9. * @author Simple Machines http://www.simplemachines.org
  10. * @copyright 2013 Simple Machines and individual contributors
  11. * @license http://www.simplemachines.org/about/smf/license.php BSD
  12. *
  13. * @version 2.1 Alpha 1
  14. */
  15. if (!defined('SMF'))
  16. die('No direct access...');
  17. /**
  18. * Check if the user is who he/she says he is
  19. * Makes sure the user is who they claim to be by requiring a 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 login, which saves all request (post and get) data.
  22. *
  23. * @param string $type = admin
  24. */
  25. function validateSession($type = 'admin')
  26. {
  27. global $modSettings, $sourcedir, $user_info, $sc, $user_settings;
  28. // We don't care if the option is off, because Guests should NEVER get past here.
  29. is_not_guest();
  30. // Validate what type of session check this is.
  31. $types = array();
  32. call_integration_hook('integrate_validateSession', array(&$types));
  33. $type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';
  34. // If we're using XML give an additional ten minutes grace as an admin can't log on in XML mode.
  35. $refreshTime = isset($_GET['xml']) ? 4200 : 3600;
  36. // Is the security option off?
  37. if (!empty($modSettings['securityDisable' . ($type != 'admin' ? '_' . $type : '')]))
  38. return;
  39. // Or are they already logged in?, Moderator or admin sesssion is need for this area
  40. if ((!empty($_SESSION[$type . '_time']) && $_SESSION[$type . '_time'] + $refreshTime >= time()) || (!empty($_SESSION['admin_time']) && $_SESSION['admin_time'] + $refreshTime >= time()))
  41. return;
  42. require_once($sourcedir . '/Subs-Auth.php');
  43. // Hashed password, ahoy!
  44. if (isset($_POST[$type . '_hash_pass']) && strlen($_POST[$type . '_hash_pass']) == 40)
  45. {
  46. checkSession();
  47. $good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST[$type . '_hash_pass'], true)), true);
  48. if ($good_password || $_POST[$type . '_hash_pass'] == sha1($user_info['passwd'] . $sc))
  49. {
  50. $_SESSION[$type . '_time'] = time();
  51. unset($_SESSION['request_referer']);
  52. return;
  53. }
  54. }
  55. // Posting the password... check it.
  56. if (isset($_POST[$type. '_pass']))
  57. {
  58. checkSession();
  59. $good_password = in_array(true, call_integration_hook('integrate_verify_password', array($user_info['username'], $_POST[$type . '_pass'], false)), true);
  60. // Password correct?
  61. if ($good_password || sha1(strtolower($user_info['username']) . $_POST[$type . '_pass']) == $user_info['passwd'])
  62. {
  63. $_SESSION[$type . '_time'] = time();
  64. unset($_SESSION['request_referer']);
  65. return;
  66. }
  67. }
  68. // OpenID?
  69. if (!empty($user_settings['openid_uri']))
  70. {
  71. require_once($sourcedir . '/Subs-OpenID.php');
  72. smf_openID_revalidate();
  73. $_SESSION[$type . '_time'] = time();
  74. unset($_SESSION['request_referer']);
  75. return;
  76. }
  77. // Better be sure to remember the real referer
  78. if (empty($_SESSION['request_referer']))
  79. $_SESSION['request_referer'] = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
  80. elseif (empty($_POST))
  81. unset($_SESSION['request_referer']);
  82. // Need to type in a password for that, man.
  83. if (!isset($_GET['xml']))
  84. adminLogin($type);
  85. else
  86. return 'session_verify_fail';
  87. }
  88. /**
  89. * Require a user who is logged in. (not a guest.)
  90. * Checks if the user is currently a guest, and if so asks them to login with a message telling them why.
  91. * Message is what to tell them when asking them to login.
  92. *
  93. * @param string $message = ''
  94. */
  95. function is_not_guest($message = '')
  96. {
  97. global $user_info, $txt, $context, $scripturl;
  98. // Luckily, this person isn't a guest.
  99. if (isset($user_info['is_guest']) && !$user_info['is_guest'])
  100. return;
  101. // People always worry when they see people doing things they aren't actually doing...
  102. $_GET['action'] = '';
  103. $_GET['board'] = '';
  104. $_GET['topic'] = '';
  105. writeLog(true);
  106. // Just die.
  107. if (isset($_REQUEST['xml']))
  108. obExit(false);
  109. // Attempt to detect if they came from dlattach.
  110. if (!WIRELESS && SMF != 'SSI' && empty($context['theme_loaded']))
  111. loadTheme();
  112. // Never redirect to an attachment
  113. if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
  114. $_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
  115. // Load the Login template and language file.
  116. loadLanguage('Login');
  117. // Are we in wireless mode?
  118. if (WIRELESS)
  119. {
  120. $context['login_error'] = $message ? $message : $txt['only_members_can_access'];
  121. $context['sub_template'] = WIRELESS_PROTOCOL . '_login';
  122. }
  123. // Apparently we're not in a position to handle this now. Let's go to a safer location for now.
  124. elseif (empty($context['template_layers']))
  125. {
  126. $_SESSION['login_url'] = $scripturl . '?' . $_SERVER['QUERY_STRING'];
  127. redirectexit('action=login');
  128. }
  129. else
  130. {
  131. loadTemplate('Login');
  132. $context['sub_template'] = 'kick_guest';
  133. $context['robot_no_index'] = true;
  134. }
  135. // Use the kick_guest sub template...
  136. $context['kick_message'] = $message;
  137. $context['page_title'] = $txt['login'];
  138. obExit();
  139. // We should never get to this point, but if we did we wouldn't know the user isn't a guest.
  140. trigger_error('Hacking attempt...', E_USER_ERROR);
  141. }
  142. /**
  143. * Do banning related stuff. (ie. disallow access....)
  144. * Checks if the user is banned, and if so dies with an error.
  145. * Caches this information for optimization purposes.
  146. * Forces a recheck if force_check is true.
  147. *
  148. * @param bool $forceCheck = false
  149. */
  150. function is_not_banned($forceCheck = false)
  151. {
  152. global $txt, $modSettings, $context, $user_info;
  153. global $sourcedir, $cookiename, $user_settings, $smcFunc;
  154. // You cannot be banned if you are an admin - doesn't help if you log out.
  155. if ($user_info['is_admin'])
  156. return;
  157. // Only check the ban every so often. (to reduce load.)
  158. 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']))
  159. {
  160. // Innocent until proven guilty. (but we know you are! :P)
  161. $_SESSION['ban'] = array(
  162. 'last_checked' => time(),
  163. 'id_member' => $user_info['id'],
  164. 'ip' => $user_info['ip'],
  165. 'ip2' => $user_info['ip2'],
  166. 'email' => $user_info['email'],
  167. );
  168. $ban_query = array();
  169. $ban_query_vars = array('current_time' => time());
  170. $flag_is_activated = false;
  171. // Check both IP addresses.
  172. foreach (array('ip', 'ip2') as $ip_number)
  173. {
  174. if ($ip_number == 'ip2' && $user_info['ip2'] == $user_info['ip'])
  175. continue;
  176. $ban_query[] = constructBanQueryIP($user_info[$ip_number]);
  177. // IP was valid, maybe there's also a hostname...
  178. if (empty($modSettings['disableHostnameLookup']) && $user_info[$ip_number] != 'unknown')
  179. {
  180. $hostname = host_from_ip($user_info[$ip_number]);
  181. if (strlen($hostname) > 0)
  182. {
  183. $ban_query[] = '({string:hostname} LIKE bi.hostname)';
  184. $ban_query_vars['hostname'] = $hostname;
  185. }
  186. }
  187. }
  188. // Is their email address banned?
  189. if (strlen($user_info['email']) != 0)
  190. {
  191. $ban_query[] = '({string:email} LIKE bi.email_address)';
  192. $ban_query_vars['email'] = $user_info['email'];
  193. }
  194. // How about this user?
  195. if (!$user_info['is_guest'] && !empty($user_info['id']))
  196. {
  197. $ban_query[] = 'bi.id_member = {int:id_member}';
  198. $ban_query_vars['id_member'] = $user_info['id'];
  199. }
  200. // Check the ban, if there's information.
  201. if (!empty($ban_query))
  202. {
  203. $restrictions = array(
  204. 'cannot_access',
  205. 'cannot_login',
  206. 'cannot_post',
  207. 'cannot_register',
  208. );
  209. $request = $smcFunc['db_query']('', '
  210. SELECT bi.id_ban, bi.email_address, bi.id_member, bg.cannot_access, bg.cannot_register,
  211. bg.cannot_post, bg.cannot_login, bg.reason, IFNULL(bg.expire_time, 0) AS expire_time
  212. FROM {db_prefix}ban_items AS bi
  213. 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}))
  214. WHERE
  215. (' . implode(' OR ', $ban_query) . ')',
  216. $ban_query_vars
  217. );
  218. // Store every type of ban that applies to you in your session.
  219. while ($row = $smcFunc['db_fetch_assoc']($request))
  220. {
  221. foreach ($restrictions as $restriction)
  222. if (!empty($row[$restriction]))
  223. {
  224. $_SESSION['ban'][$restriction]['reason'] = $row['reason'];
  225. $_SESSION['ban'][$restriction]['ids'][] = $row['id_ban'];
  226. if (!isset($_SESSION['ban']['expire_time']) || ($_SESSION['ban']['expire_time'] != 0 && ($row['expire_time'] == 0 || $row['expire_time'] > $_SESSION['ban']['expire_time'])))
  227. $_SESSION['ban']['expire_time'] = $row['expire_time'];
  228. if (!$user_info['is_guest'] && $restriction == 'cannot_access' && ($row['id_member'] == $user_info['id'] || $row['email_address'] == $user_info['email']))
  229. $flag_is_activated = true;
  230. }
  231. }
  232. $smcFunc['db_free_result']($request);
  233. }
  234. // Mark the cannot_access and cannot_post bans as being 'hit'.
  235. if (isset($_SESSION['ban']['cannot_access']) || isset($_SESSION['ban']['cannot_post']) || isset($_SESSION['ban']['cannot_login']))
  236. 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()));
  237. // If for whatever reason the is_activated flag seems wrong, do a little work to clear it up.
  238. if ($user_info['id'] && (($user_settings['is_activated'] >= 10 && !$flag_is_activated)
  239. || ($user_settings['is_activated'] < 10 && $flag_is_activated)))
  240. {
  241. require_once($sourcedir . '/ManageBans.php');
  242. updateBanMembers();
  243. }
  244. }
  245. // Hey, I know you! You're ehm...
  246. if (!isset($_SESSION['ban']['cannot_access']) && !empty($_COOKIE[$cookiename . '_']))
  247. {
  248. $bans = explode(',', $_COOKIE[$cookiename . '_']);
  249. foreach ($bans as $key => $value)
  250. $bans[$key] = (int) $value;
  251. $request = $smcFunc['db_query']('', '
  252. SELECT bi.id_ban, bg.reason
  253. FROM {db_prefix}ban_items AS bi
  254. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  255. WHERE bi.id_ban IN ({array_int:ban_list})
  256. AND (bg.expire_time IS NULL OR bg.expire_time > {int:current_time})
  257. AND bg.cannot_access = {int:cannot_access}
  258. LIMIT ' . count($bans),
  259. array(
  260. 'cannot_access' => 1,
  261. 'ban_list' => $bans,
  262. 'current_time' => time(),
  263. )
  264. );
  265. while ($row = $smcFunc['db_fetch_assoc']($request))
  266. {
  267. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  268. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  269. }
  270. $smcFunc['db_free_result']($request);
  271. // My mistake. Next time better.
  272. if (!isset($_SESSION['ban']['cannot_access']))
  273. {
  274. require_once($sourcedir . '/Subs-Auth.php');
  275. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  276. smf_setcookie($cookiename . '_', '', time() - 3600, $cookie_url[1], $cookie_url[0], false, false);
  277. }
  278. }
  279. // If you're fully banned, it's end of the story for you.
  280. if (isset($_SESSION['ban']['cannot_access']))
  281. {
  282. // We don't wanna see you!
  283. if (!$user_info['is_guest'])
  284. $smcFunc['db_query']('', '
  285. DELETE FROM {db_prefix}log_online
  286. WHERE id_member = {int:current_member}',
  287. array(
  288. 'current_member' => $user_info['id'],
  289. )
  290. );
  291. // 'Log' the user out. Can't have any funny business... (save the name!)
  292. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  293. $user_info['name'] = '';
  294. $user_info['username'] = '';
  295. $user_info['is_guest'] = true;
  296. $user_info['is_admin'] = false;
  297. $user_info['permissions'] = array();
  298. $user_info['id'] = 0;
  299. $context['user'] = array(
  300. 'id' => 0,
  301. 'username' => '',
  302. 'name' => $txt['guest_title'],
  303. 'is_guest' => true,
  304. 'is_logged' => false,
  305. 'is_admin' => false,
  306. 'is_mod' => false,
  307. 'can_mod' => false,
  308. 'language' => $user_info['language'],
  309. );
  310. // A goodbye present.
  311. require_once($sourcedir . '/Subs-Auth.php');
  312. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  313. smf_setcookie($cookiename . '_', implode(',', $_SESSION['ban']['cannot_access']['ids']), time() + 3153600, $cookie_url[1], $cookie_url[0], false, false);
  314. // Don't scare anyone, now.
  315. $_GET['action'] = '';
  316. $_GET['board'] = '';
  317. $_GET['topic'] = '';
  318. writeLog(true);
  319. // You banned, sucka!
  320. 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']), !empty($modSettings['log_ban_hits']) ? 'ban' : false);
  321. // If we get here, something's gone wrong.... but let's try anyway.
  322. trigger_error('Hacking attempt...', E_USER_ERROR);
  323. }
  324. // You're not allowed to log in but yet you are. Let's fix that.
  325. elseif (isset($_SESSION['ban']['cannot_login']) && !$user_info['is_guest'])
  326. {
  327. // We don't wanna see you!
  328. $smcFunc['db_query']('', '
  329. DELETE FROM {db_prefix}log_online
  330. WHERE id_member = {int:current_member}',
  331. array(
  332. 'current_member' => $user_info['id'],
  333. )
  334. );
  335. // 'Log' the user out. Can't have any funny business... (save the name!)
  336. $old_name = isset($user_info['name']) && $user_info['name'] != '' ? $user_info['name'] : $txt['guest_title'];
  337. $user_info['name'] = '';
  338. $user_info['username'] = '';
  339. $user_info['is_guest'] = true;
  340. $user_info['is_admin'] = false;
  341. $user_info['permissions'] = array();
  342. $user_info['id'] = 0;
  343. $context['user'] = array(
  344. 'id' => 0,
  345. 'username' => '',
  346. 'name' => $txt['guest_title'],
  347. 'is_guest' => true,
  348. 'is_logged' => false,
  349. 'is_admin' => false,
  350. 'is_mod' => false,
  351. 'can_mod' => false,
  352. 'language' => $user_info['language'],
  353. );
  354. // SMF's Wipe 'n Clean(r) erases all traces.
  355. $_GET['action'] = '';
  356. $_GET['board'] = '';
  357. $_GET['topic'] = '';
  358. writeLog(true);
  359. require_once($sourcedir . '/LogInOut.php');
  360. Logout(true, false);
  361. 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'], !empty($modSettings['log_ban_hits']) ? 'ban' : false);
  362. }
  363. // Fix up the banning permissions.
  364. if (isset($user_info['permissions']))
  365. banPermissions();
  366. }
  367. /**
  368. * Fix permissions according to ban status.
  369. * Applies any states of banning by removing permissions the user cannot have.
  370. */
  371. function banPermissions()
  372. {
  373. global $user_info, $sourcedir, $modSettings, $context;
  374. // Somehow they got here, at least take away all permissions...
  375. if (isset($_SESSION['ban']['cannot_access']))
  376. $user_info['permissions'] = array();
  377. // Okay, well, you can watch, but don't touch a thing.
  378. elseif (isset($_SESSION['ban']['cannot_post']) || (!empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $user_info['warning']))
  379. {
  380. $denied_permissions = array(
  381. 'pm_send',
  382. 'calendar_post', 'calendar_edit_own', 'calendar_edit_any',
  383. 'poll_post',
  384. 'poll_add_own', 'poll_add_any',
  385. 'poll_edit_own', 'poll_edit_any',
  386. 'poll_lock_own', 'poll_lock_any',
  387. 'poll_remove_own', 'poll_remove_any',
  388. 'manage_attachments', 'manage_smileys', 'manage_boards', 'admin_forum', 'manage_permissions',
  389. 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news',
  390. 'profile_identity_any', 'profile_extra_any', 'profile_title_any',
  391. 'post_new', 'post_reply_own', 'post_reply_any',
  392. 'delete_own', 'delete_any', 'delete_replies',
  393. 'make_sticky',
  394. 'merge_any', 'split_any',
  395. 'modify_own', 'modify_any', 'modify_replies',
  396. 'move_any',
  397. 'send_topic',
  398. 'lock_own', 'lock_any',
  399. 'remove_own', 'remove_any',
  400. 'post_unapproved_topics', 'post_unapproved_replies_own', 'post_unapproved_replies_any',
  401. );
  402. call_integration_hook('integrate_post_ban_permissions', array(&$denied_permissions));
  403. $user_info['permissions'] = array_diff($user_info['permissions'], $denied_permissions);
  404. }
  405. // Are they absolutely under moderation?
  406. elseif (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $user_info['warning'])
  407. {
  408. // Work out what permissions should change...
  409. $permission_change = array(
  410. 'post_new' => 'post_unapproved_topics',
  411. 'post_reply_own' => 'post_unapproved_replies_own',
  412. 'post_reply_any' => 'post_unapproved_replies_any',
  413. 'post_attachment' => 'post_unapproved_attachments',
  414. );
  415. call_integration_hook('integrate_warn_permissions', array(&$permission_change));
  416. foreach ($permission_change as $old => $new)
  417. {
  418. if (!in_array($old, $user_info['permissions']))
  419. unset($permission_change[$old]);
  420. else
  421. $user_info['permissions'][] = $new;
  422. }
  423. $user_info['permissions'] = array_diff($user_info['permissions'], array_keys($permission_change));
  424. }
  425. // @todo Find a better place to call this? Needs to be after permissions loaded!
  426. // Finally, some bits we cache in the session because it saves queries.
  427. if (isset($_SESSION['mc']) && $_SESSION['mc']['time'] > $modSettings['settings_updated'] && $_SESSION['mc']['id'] == $user_info['id'])
  428. $user_info['mod_cache'] = $_SESSION['mc'];
  429. else
  430. {
  431. require_once($sourcedir . '/Subs-Auth.php');
  432. rebuildModCache();
  433. }
  434. // Now that we have the mod cache taken care of lets setup a cache for the number of mod reports still open
  435. if (isset($_SESSION['rc']) && $_SESSION['rc']['time'] > $modSettings['last_mod_report_action'] && $_SESSION['rc']['id'] == $user_info['id'])
  436. $context['open_mod_reports'] = $_SESSION['rc']['reports'];
  437. elseif ($_SESSION['mc']['bq'] != '0=1')
  438. {
  439. require_once($sourcedir . '/ModerationCenter.php');
  440. recountOpenReports();
  441. }
  442. else
  443. $context['open_mod_reports'] = 0;
  444. }
  445. /**
  446. * Log a ban in the database.
  447. * Log the current user in the ban logs.
  448. * Increment the hit counters for the specified ban ID's (if any.)
  449. *
  450. * @param array $ban_ids = array()
  451. * @param string $email = null
  452. */
  453. function log_ban($ban_ids = array(), $email = null)
  454. {
  455. global $user_info, $smcFunc;
  456. // Don't log web accelerators, it's very confusing...
  457. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  458. return;
  459. $smcFunc['db_insert']('',
  460. '{db_prefix}log_banned',
  461. array('id_member' => 'int', 'ip' => 'string-16', 'email' => 'string', 'log_time' => 'int'),
  462. array($user_info['id'], $user_info['ip'], ($email === null ? ($user_info['is_guest'] ? '' : $user_info['email']) : $email), time()),
  463. array('id_ban_log')
  464. );
  465. // One extra point for these bans.
  466. if (!empty($ban_ids))
  467. $smcFunc['db_query']('', '
  468. UPDATE {db_prefix}ban_items
  469. SET hits = hits + 1
  470. WHERE id_ban IN ({array_int:ban_ids})',
  471. array(
  472. 'ban_ids' => $ban_ids,
  473. )
  474. );
  475. }
  476. /**
  477. * Checks if a given email address might be banned.
  478. * Check if a given email is banned.
  479. * Performs an immediate ban if the turns turns out positive.
  480. *
  481. * @param string $email
  482. * @param string $restriction
  483. * @param string $error
  484. */
  485. function isBannedEmail($email, $restriction, $error)
  486. {
  487. global $txt, $smcFunc;
  488. // Can't ban an empty email
  489. if (empty($email) || trim($email) == '')
  490. return;
  491. // Let's start with the bans based on your IP/hostname/memberID...
  492. $ban_ids = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['ids'] : array();
  493. $ban_reason = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['reason'] : '';
  494. // ...and add to that the email address you're trying to register.
  495. $request = $smcFunc['db_query']('', '
  496. SELECT bi.id_ban, bg.' . $restriction . ', bg.cannot_access, bg.reason
  497. FROM {db_prefix}ban_items AS bi
  498. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  499. WHERE {string:email} LIKE bi.email_address
  500. AND (bg.' . $restriction . ' = {int:cannot_access} OR bg.cannot_access = {int:cannot_access})
  501. AND (bg.expire_time IS NULL OR bg.expire_time >= {int:now})',
  502. array(
  503. 'email' => $email,
  504. 'cannot_access' => 1,
  505. 'now' => time(),
  506. )
  507. );
  508. while ($row = $smcFunc['db_fetch_assoc']($request))
  509. {
  510. if (!empty($row['cannot_access']))
  511. {
  512. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  513. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  514. }
  515. if (!empty($row[$restriction]))
  516. {
  517. $ban_ids[] = $row['id_ban'];
  518. $ban_reason = $row['reason'];
  519. }
  520. }
  521. $smcFunc['db_free_result']($request);
  522. // You're in biiig trouble. Banned for the rest of this session!
  523. if (isset($_SESSION['ban']['cannot_access']))
  524. {
  525. log_ban($_SESSION['ban']['cannot_access']['ids']);
  526. $_SESSION['ban']['last_checked'] = time();
  527. fatal_error(sprintf($txt['your_ban'], $txt['guest_title']) . $_SESSION['ban']['cannot_access']['reason'], false);
  528. }
  529. if (!empty($ban_ids))
  530. {
  531. // Log this ban for future reference.
  532. log_ban($ban_ids, $email);
  533. fatal_error($error . $ban_reason, false);
  534. }
  535. }
  536. /**
  537. * Make sure the user's correct session was passed, and they came from here.
  538. * Checks the current session, verifying that the person is who he or she should be.
  539. * Also checks the referrer to make sure they didn't get sent here.
  540. * Depends on the disableCheckUA setting, which is usually missing.
  541. * Will check GET, POST, or REQUEST depending on the passed type.
  542. * Also optionally checks the referring action if passed. (note that the referring action must be by GET.)
  543. *
  544. * @param string $type = 'post' (post, get, request)
  545. * @param string $from_action = ''
  546. * @param bool $is_fatal = true
  547. * @return string the error message if is_fatal is false.
  548. */
  549. function checkSession($type = 'post', $from_action = '', $is_fatal = true)
  550. {
  551. global $sc, $modSettings, $boardurl;
  552. // Is it in as $_POST['sc']?
  553. if ($type == 'post')
  554. {
  555. $check = isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null);
  556. if ($check !== $sc)
  557. $error = 'session_timeout';
  558. }
  559. // How about $_GET['sesc']?
  560. elseif ($type == 'get')
  561. {
  562. $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : null);
  563. if ($check !== $sc)
  564. $error = 'session_verify_fail';
  565. }
  566. // Or can it be in either?
  567. elseif ($type == 'request')
  568. {
  569. $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)));
  570. if ($check !== $sc)
  571. $error = 'session_verify_fail';
  572. }
  573. // Verify that they aren't changing user agents on us - that could be bad.
  574. if ((!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] != $_SERVER['HTTP_USER_AGENT']) && empty($modSettings['disableCheckUA']))
  575. $error = 'session_verify_fail';
  576. // Make sure a page with session check requirement is not being prefetched.
  577. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  578. {
  579. ob_end_clean();
  580. header('HTTP/1.1 403 Forbidden');
  581. die;
  582. }
  583. // Check the referring site - it should be the same server at least!
  584. if (isset($_SESSION['request_referer']))
  585. $referrer = $_SESSION['request_referer'];
  586. else
  587. $referrer = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
  588. if (!empty($referrer['host']))
  589. {
  590. if (strpos($_SERVER['HTTP_HOST'], ':') !== false)
  591. $real_host = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
  592. else
  593. $real_host = $_SERVER['HTTP_HOST'];
  594. $parsed_url = parse_url($boardurl);
  595. // Are global cookies on? If so, let's check them ;).
  596. if (!empty($modSettings['globalCookies']))
  597. {
  598. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  599. $parsed_url['host'] = $parts[1];
  600. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $referrer['host'], $parts) == 1)
  601. $referrer['host'] = $parts[1];
  602. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $real_host, $parts) == 1)
  603. $real_host = $parts[1];
  604. }
  605. // Okay: referrer must either match parsed_url or real_host.
  606. if (isset($parsed_url['host']) && strtolower($referrer['host']) != strtolower($parsed_url['host']) && strtolower($referrer['host']) != strtolower($real_host))
  607. {
  608. $error = 'verify_url_fail';
  609. $log_error = true;
  610. }
  611. }
  612. // Well, first of all, if a from_action is specified you'd better have an old_url.
  613. if (!empty($from_action) && (!isset($_SESSION['old_url']) || preg_match('~[?;&]action=' . $from_action . '([;&]|$)~', $_SESSION['old_url']) == 0))
  614. {
  615. $error = 'verify_url_fail';
  616. $log_error = true;
  617. }
  618. if (strtolower($_SERVER['HTTP_USER_AGENT']) == 'hacker')
  619. fatal_error('Sound the alarm! It\'s a hacker! Close the castle gates!!', false);
  620. // Everything is ok, return an empty string.
  621. if (!isset($error))
  622. return '';
  623. // A session error occurred, show the error.
  624. elseif ($is_fatal)
  625. {
  626. if (isset($_GET['xml']))
  627. {
  628. ob_end_clean();
  629. header('HTTP/1.1 403 Forbidden - Session timeout');
  630. die;
  631. }
  632. else
  633. fatal_lang_error($error, isset($log_error) ? 'user' : false);
  634. }
  635. // A session error occurred, return the error to the calling function.
  636. else
  637. return $error;
  638. // We really should never fall through here, for very important reasons. Let's make sure.
  639. trigger_error('Hacking attempt...', E_USER_ERROR);
  640. }
  641. /**
  642. * Check if a specific confirm parameter was given.
  643. *
  644. * @param string $action
  645. */
  646. function checkConfirm($action)
  647. {
  648. global $modSettings;
  649. if (isset($_GET['confirm']) && isset($_SESSION['confirm_' . $action]) && md5($_GET['confirm'] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['confirm_' . $action])
  650. return true;
  651. else
  652. {
  653. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed']);
  654. $_SESSION['confirm_' . $action] = md5($token . $_SERVER['HTTP_USER_AGENT']);
  655. return $token;
  656. }
  657. }
  658. /**
  659. * Lets give you a token of our appreciation.
  660. *
  661. * @param string $action
  662. * @param string $type = 'post'
  663. * @return array
  664. */
  665. function createToken($action, $type = 'post')
  666. {
  667. global $modSettings, $context;
  668. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed'] . $type);
  669. $token_var = substr(preg_replace('~^\d+~', '', md5(mt_rand() . (string) microtime() . mt_rand())), 0, rand(7, 12));
  670. $_SESSION['token'][$type . '-' . $action] = array($token_var, md5($token . $_SERVER['HTTP_USER_AGENT']), time(), $token);
  671. $context[$action . '_token'] = $token;
  672. $context[$action . '_token_var'] = $token_var;
  673. return array($action . '_token_var' => $token_var, $action . '_token' => $token);
  674. }
  675. /**
  676. * Only patrons with valid tokens can ride this ride.
  677. *
  678. * @param string $action
  679. * @param string $type = 'post' (get, request, or post)
  680. * @param bool $reset = true
  681. * @return boolean
  682. */
  683. function validateToken($action, $type = 'post', $reset = true)
  684. {
  685. global $modSettings, $db_show_debug;
  686. $type = $type == 'get' || $type == 'request' ? $type : 'post';
  687. // Logins are special: the token is used to has the password with javascript before POST it
  688. if ($action == 'login')
  689. {
  690. if (isset($_SESSION['token'][$type . '-' . $action]))
  691. {
  692. $return = $_SESSION['token'][$type . '-' . $action][3];
  693. unset($_SESSION['token'][$type . '-' . $action]);
  694. return $return;
  695. }
  696. else
  697. return '';
  698. }
  699. // This nasty piece of code validates a token.
  700. /*
  701. 1. The token exists in session.
  702. 2. The {$type} variable should exist.
  703. 3. We concat the variable we received with the user agent
  704. 4. Match that result against what is in the session.
  705. 5. If it matchs, success, otherwise we fallout.
  706. */
  707. 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])
  708. {
  709. // Invalidate this token now.
  710. unset($_SESSION['token'][$type . '-' . $action]);
  711. return true;
  712. }
  713. // Patrons with invalid tokens get the boot.
  714. if ($reset)
  715. {
  716. // Might as well do some cleanup on this.
  717. cleanTokens();
  718. // I'm back baby.
  719. createToken($action, $type);
  720. fatal_lang_error('token_verify_fail', false);
  721. }
  722. // Remove this token as its useless
  723. else
  724. unset($_SESSION['token'][$type . '-' . $action]);
  725. // Randomly check if we should remove some older tokens.
  726. if (mt_rand(0, 138) == 23)
  727. cleanTokens();
  728. return false;
  729. }
  730. /**
  731. * Removes old unused tokens from session
  732. * defaults to 3 hours before a token is considered expired
  733. * if $complete = true will remove all tokens
  734. *
  735. * @param bool $complete = false
  736. */
  737. function cleanTokens($complete = false)
  738. {
  739. // We appreciate cleaning up after yourselves.
  740. if (!isset($_SESSION['token']))
  741. return;
  742. // Clean up tokens, trying to give enough time still.
  743. foreach ($_SESSION['token'] as $key => $data)
  744. if ($data[2] + 10800 < time() || $complete)
  745. unset($_SESSION['token'][$key]);
  746. }
  747. /**
  748. * Check whether a form has been submitted twice.
  749. * Registers a sequence number for a form.
  750. * Checks whether a submitted sequence number is registered in the current session.
  751. * Depending on the value of is_fatal shows an error or returns true or false.
  752. * Frees a sequence number from the stack after it's been checked.
  753. * Frees a sequence number without checking if action == 'free'.
  754. *
  755. * @param string $action
  756. * @param bool $is_fatal = true
  757. * @return boolean
  758. */
  759. function checkSubmitOnce($action, $is_fatal = true)
  760. {
  761. global $context;
  762. if (!isset($_SESSION['forms']))
  763. $_SESSION['forms'] = array();
  764. // Register a form number and store it in the session stack. (use this on the page that has the form.)
  765. if ($action == 'register')
  766. {
  767. $context['form_sequence_number'] = 0;
  768. while (empty($context['form_sequence_number']) || in_array($context['form_sequence_number'], $_SESSION['forms']))
  769. $context['form_sequence_number'] = mt_rand(1, 16000000);
  770. }
  771. // Check whether the submitted number can be found in the session.
  772. elseif ($action == 'check')
  773. {
  774. if (!isset($_REQUEST['seqnum']))
  775. return true;
  776. elseif (!in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  777. {
  778. $_SESSION['forms'][] = (int) $_REQUEST['seqnum'];
  779. return true;
  780. }
  781. elseif ($is_fatal)
  782. fatal_lang_error('error_form_already_submitted', false);
  783. else
  784. return false;
  785. }
  786. // Don't check, just free the stack number.
  787. elseif ($action == 'free' && isset($_REQUEST['seqnum']) && in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  788. $_SESSION['forms'] = array_diff($_SESSION['forms'], array($_REQUEST['seqnum']));
  789. elseif ($action != 'free')
  790. trigger_error('checkSubmitOnce(): Invalid action \'' . $action . '\'', E_USER_WARNING);
  791. }
  792. /**
  793. * Check the user's permissions.
  794. * checks whether the user is allowed to do permission. (ie. post_new.)
  795. * If boards is specified, checks those boards instead of the current one.
  796. * Always returns true if the user is an administrator.
  797. *
  798. * @param string $permission
  799. * @param array $boards = null
  800. * @return boolean if the user can do the permission
  801. */
  802. function allowedTo($permission, $boards = null)
  803. {
  804. global $user_info, $modSettings, $smcFunc;
  805. // You're always allowed to do nothing. (unless you're a working man, MR. LAZY :P!)
  806. if (empty($permission))
  807. return true;
  808. // You're never allowed to do something if your data hasn't been loaded yet!
  809. if (empty($user_info))
  810. return false;
  811. // Administrators are supermen :P.
  812. if ($user_info['is_admin'])
  813. return true;
  814. // Are we checking the _current_ board, or some other boards?
  815. if ($boards === null)
  816. {
  817. // Check if they can do it.
  818. if (!is_array($permission) && in_array($permission, $user_info['permissions']))
  819. return true;
  820. // Search for any of a list of permissions.
  821. elseif (is_array($permission) && count(array_intersect($permission, $user_info['permissions'])) != 0)
  822. return true;
  823. // You aren't allowed, by default.
  824. else
  825. return false;
  826. }
  827. elseif (!is_array($boards))
  828. $boards = array($boards);
  829. $request = $smcFunc['db_query']('', '
  830. SELECT MIN(bp.add_deny) AS add_deny
  831. FROM {db_prefix}boards AS b
  832. INNER JOIN {db_prefix}board_permissions AS bp ON (bp.id_profile = b.id_profile)
  833. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  834. LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND b.id_group IN ({array_int:group_list})
  835. WHERE b.id_board IN ({array_int:board_list})
  836. AND bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  837. AND bp.permission {raw:permission_list}
  838. AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})
  839. GROUP BY b.id_board',
  840. array(
  841. 'current_member' => $user_info['id'],
  842. 'board_list' => $boards,
  843. 'group_list' => $user_info['groups'],
  844. 'moderator_group' => 3,
  845. 'permission_list' => (is_array($permission) ? 'IN (\'' . implode('\', \'', $permission) . '\')' : ' = \'' . $permission . '\''),
  846. )
  847. );
  848. // Make sure they can do it on all of the boards.
  849. if ($smcFunc['db_num_rows']($request) != count($boards))
  850. return false;
  851. $result = true;
  852. while ($row = $smcFunc['db_fetch_assoc']($request))
  853. $result &= !empty($row['add_deny']);
  854. $smcFunc['db_free_result']($request);
  855. // If the query returned 1, they can do it... otherwise, they can't.
  856. return $result;
  857. }
  858. /**
  859. * Fatal error if they cannot.
  860. * Uses allowedTo() to check if the user is allowed to do permission.
  861. * Checks the passed boards or current board for the permission.
  862. * If they are not, it loads the Errors language file and shows an error using $txt['cannot_' . $permission].
  863. * If they are a guest and cannot do it, this calls is_not_guest().
  864. *
  865. * @param string $permission
  866. * @param array $boards = null
  867. */
  868. function isAllowedTo($permission, $boards = null)
  869. {
  870. global $user_info, $txt;
  871. static $heavy_permissions = array(
  872. 'admin_forum',
  873. 'manage_attachments',
  874. 'manage_smileys',
  875. 'manage_boards',
  876. 'edit_news',
  877. 'moderate_forum',
  878. 'manage_bans',
  879. 'manage_membergroups',
  880. 'manage_permissions',
  881. );
  882. // Make it an array, even if a string was passed.
  883. $permission = is_array($permission) ? $permission : array($permission);
  884. // Check the permission and return an error...
  885. if (!allowedTo($permission, $boards))
  886. {
  887. // Pick the last array entry as the permission shown as the error.
  888. $error_permission = array_shift($permission);
  889. // If they are a guest, show a login. (because the error might be gone if they do!)
  890. if ($user_info['is_guest'])
  891. {
  892. loadLanguage('Errors');
  893. is_not_guest($txt['cannot_' . $error_permission]);
  894. }
  895. // Clear the action because they aren't really doing that!
  896. $_GET['action'] = '';
  897. $_GET['board'] = '';
  898. $_GET['topic'] = '';
  899. writeLog(true);
  900. fatal_lang_error('cannot_' . $error_permission, false);
  901. // Getting this far is a really big problem, but let's try our best to prevent any cases...
  902. trigger_error('Hacking attempt...', E_USER_ERROR);
  903. }
  904. // If you're doing something on behalf of some "heavy" permissions, validate your session.
  905. // (take out the heavy permissions, and if you can't do anything but those, you need a validated session.)
  906. if (!allowedTo(array_diff($permission, $heavy_permissions), $boards))
  907. validateSession();
  908. }
  909. /**
  910. * Return the boards a user has a certain (board) permission on. (array(0) if all.)
  911. * - returns a list of boards on which the user is allowed to do the specified permission.
  912. * - returns an array with only a 0 in it if the user has permission to do this on every board.
  913. * - returns an empty array if he or she cannot do this on any board.
  914. * If check_access is true will also make sure the group has proper access to that board.
  915. *
  916. * @param array $permissions
  917. * @param bool $check_access = true
  918. * @param bool $simple = true
  919. */
  920. function boardsAllowedTo($permissions, $check_access = true, $simple = true)
  921. {
  922. global $user_info, $modSettings, $smcFunc;
  923. // Arrays are nice, most of the time.
  924. if (!is_array($permissions))
  925. $permissions = array($permissions);
  926. /*
  927. * Set $simple to true to use this function as it were in SMF 2.0.x.
  928. * Otherwise, the resultant array becomes split into the multiple
  929. * permissions that were passed. Other than that, it's just the normal
  930. * state of play that you're used to.
  931. */
  932. // Administrators are all powerful, sorry.
  933. if ($user_info['is_admin'])
  934. {
  935. if ($simple)
  936. return array(0);
  937. else
  938. {
  939. $boards = array();
  940. foreach ($permissions as $permission)
  941. $boards[$permission] = array(0);
  942. return $boards;
  943. }
  944. }
  945. // All groups the user is in except 'moderator'.
  946. $groups = array_diff($user_info['groups'], array(3));
  947. $request = $smcFunc['db_query']('', '
  948. SELECT b.id_board, bp.add_deny' . ($simple ? '' : ', bp.permission') . '
  949. FROM {db_prefix}board_permissions AS bp
  950. INNER JOIN {db_prefix}boards AS b ON (b.id_profile = bp.id_profile)
  951. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  952. LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND modgs.id_group IN ({array_int:group_list}))
  953. WHERE bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  954. AND bp.permission IN ({array_string:permissions})
  955. AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})' .
  956. ($check_access ? ' AND {query_see_board}' : ''),
  957. array(
  958. 'current_member' => $user_info['id'],
  959. 'group_list' => $groups,
  960. 'moderator_group' => 3,
  961. 'permissions' => $permissions,
  962. )
  963. );
  964. $boards = array();
  965. $deny_boards = array();
  966. while ($row = $smcFunc['db_fetch_assoc']($request))
  967. {
  968. if ($simple)
  969. {
  970. if (empty($row['add_deny']))
  971. $deny_boards[] = $row['id_board'];
  972. else
  973. $boards[] = $row['id_board'];
  974. }
  975. else
  976. {
  977. if (empty($row['add_deny']))
  978. $deny_boards[$row['permission']][] = $row['id_board'];
  979. else
  980. $boards[$row['permission']][] = $row['id_board'];
  981. }
  982. }
  983. $smcFunc['db_free_result']($request);
  984. if ($simple)
  985. $boards = array_unique(array_values(array_diff($boards, $deny_boards)));
  986. else
  987. {
  988. foreach ($permissions as $permission)
  989. {
  990. // never had it to start with
  991. if (empty($boards[$permission]))
  992. $boards[$permission] = array();
  993. else
  994. {
  995. // Or it may have been removed
  996. $deny_boards[$permission] = isset($deny_boards[$permission]) ? $deny_boards[$permission] : array();
  997. $boards[$permission] = array_unique(array_values(array_diff($boards[$permission], $deny_boards[$permission])));
  998. }
  999. }
  1000. }
  1001. return $boards;
  1002. }
  1003. /**
  1004. * Returns whether an email address should be shown and how.
  1005. * Possible outcomes are
  1006. * 'yes': show the full email address
  1007. * 'yes_permission_override': show the full email address, either you
  1008. * are a moderator or it's your own email address.
  1009. * 'no_through_forum': don't show the email address, but do allow
  1010. * things to be mailed using the built-in forum mailer.
  1011. * 'no': keep the email address hidden.
  1012. *
  1013. * @param bool $userProfile_hideEmail
  1014. * @param int $userProfile_id
  1015. * @return string (yes, yes_permission_override, no_through_forum, no)
  1016. */
  1017. function showEmailAddress($userProfile_hideEmail, $userProfile_id)
  1018. {
  1019. global $modSettings, $user_info;
  1020. // Should this user's email address be shown?
  1021. // If you're guest and the forum is set to hide email for guests: no.
  1022. // If the user is post-banned: no.
  1023. // If it's your own profile and you've set your address hidden: yes_permission_override.
  1024. // If you're a moderator with sufficient permissions: yes_permission_override.
  1025. // If the user has set their email address to be hidden: no.
  1026. // If the forum is set to show full email addresses: yes.
  1027. // Otherwise: no_through_forum.
  1028. if ($user_info['is_guest'] || isset($_SESSION['ban']['cannot_post']))
  1029. return 'no';
  1030. elseif ((!$user_info['is_guest'] && $user_info['id'] == $userProfile_id && !$userProfile_hideEmail) || allowedTo('moderate_forum'))
  1031. return 'yes_permission_override';
  1032. elseif ($userProfile_hideEmail)
  1033. return 'no';
  1034. elseif (!empty($modSettings['make_email_viewable']) )
  1035. return 'yes';
  1036. else
  1037. return 'no_through_forum';
  1038. }
  1039. /**
  1040. * This function attempts to protect from spammed messages and the like.
  1041. * The time taken depends on error_type - generally uses the modSetting.
  1042. *
  1043. * @param string $error_type used also as a $txt index. (not an actual string.)
  1044. * @return boolean
  1045. */
  1046. function spamProtection($error_type)
  1047. {
  1048. global $modSettings, $txt, $user_info, $smcFunc;
  1049. // Certain types take less/more time.
  1050. $timeOverrides = array(
  1051. 'login' => 2,
  1052. 'register' => 2,
  1053. 'remind' => 30,
  1054. 'sendtopic' => $modSettings['spamWaitTime'] * 4,
  1055. 'sendmail' => $modSettings['spamWaitTime'] * 5,
  1056. 'reporttm' => $modSettings['spamWaitTime'] * 4,
  1057. 'search' => !empty($modSettings['search_floodcontrol_time']) ? $modSettings['search_floodcontrol_time'] : 1,
  1058. );
  1059. call_integration_hook('integrate_spam_protection', array(&$timeOverrides));
  1060. // Moderators are free...
  1061. if (!allowedTo('moderate_board'))
  1062. $timeLimit = isset($timeOverrides[$error_type]) ? $timeOverrides[$error_type] : $modSettings['spamWaitTime'];
  1063. else
  1064. $timeLimit = 2;
  1065. // Delete old entries...
  1066. $smcFunc['db_query']('', '
  1067. DELETE FROM {db_prefix}log_floodcontrol
  1068. WHERE log_time < {int:log_time}
  1069. AND log_type = {string:log_type}',
  1070. array(
  1071. 'log_time' => time() - $timeLimit,
  1072. 'log_type' => $error_type,
  1073. )
  1074. );
  1075. // Add a new entry, deleting the old if necessary.
  1076. $smcFunc['db_insert']('replace',
  1077. '{db_prefix}log_floodcontrol',
  1078. array('ip' => 'string-16', 'log_time' => 'int', 'log_type' => 'string'),
  1079. array($user_info['ip'], time(), $error_type),
  1080. array('ip', 'log_type')
  1081. );
  1082. // If affected is 0 or 2, it was there already.
  1083. if ($smcFunc['db_affected_rows']() != 1)
  1084. {
  1085. // Spammer! You only have to wait a *few* seconds!
  1086. fatal_lang_error($error_type . '_WaitTime_broken', false, array($timeLimit));
  1087. return true;
  1088. }
  1089. // They haven't posted within the limit.
  1090. return false;
  1091. }
  1092. /**
  1093. * A generic function to create a pair of index.php and .htaccess files in a directory
  1094. *
  1095. * @param string $path the (absolute) directory path
  1096. * @param boolean $attachments if the directory is an attachments directory or not
  1097. * @return true on success error string if anything fails
  1098. */
  1099. function secureDirectory($path, $attachments = false)
  1100. {
  1101. if (empty($path))
  1102. return 'empty_path';
  1103. if (!is_writable($path))
  1104. return 'path_not_writable';
  1105. $directoryname = basename($path);
  1106. $errors = array();
  1107. $close = empty($attachments) ? '
  1108. </Files>' : '
  1109. Allow from localhost
  1110. </Files>
  1111. RemoveHandler .php .php3 .phtml .cgi .fcgi .pl .fpl .shtml';
  1112. if (file_exists($path . '/.htaccess'))
  1113. $errors[] = 'htaccess_exists';
  1114. else
  1115. {
  1116. $fh = @fopen($path . '/.htaccess', 'w');
  1117. if ($fh) {
  1118. fwrite($fh, '<Files *>
  1119. Order Deny,Allow
  1120. Deny from all' . $close);
  1121. fclose($fh);
  1122. }
  1123. $errors[] = 'htaccess_cannot_create_file';
  1124. }
  1125. if (file_exists($path . '/index.php'))
  1126. $errors[] = 'index-php_exists';
  1127. else
  1128. {
  1129. $fh = @fopen($path . '/index.php', 'w');
  1130. if ($fh) {
  1131. fwrite($fh, '<' . '?php
  1132. /**
  1133. * This file is here solely to protect your ' . $directoryname . ' directory.
  1134. */
  1135. // Look for Settings.php....
  1136. if (file_exists(dirname(dirname(__FILE__)) . \'/Settings.php\'))
  1137. {
  1138. // Found it!
  1139. require(dirname(dirname(__FILE__)) . \'/Settings.php\');
  1140. header(\'Location: \' . $boardurl);
  1141. }
  1142. // Can\'t find it... just forget it.
  1143. else
  1144. exit;
  1145. ?'. '>');
  1146. fclose($fh);
  1147. }
  1148. $errors[] = 'index-php_cannot_create_file';
  1149. }
  1150. if (!empty($errors))
  1151. return $errors;
  1152. else
  1153. return true;
  1154. }
  1155. /**
  1156. * Helper function that puts together a ban query for a given ip
  1157. * builds the query for ipv6, ipv4 or 255.255.255.255 depending on whats supplied
  1158. *
  1159. * @param string $fullip An IP address either IPv6 or not
  1160. * @return string A SQL condition
  1161. */
  1162. function constructBanQueryIP($fullip)
  1163. {
  1164. // First attempt a IPv6 address.
  1165. if (isValidIPv6($fullip))
  1166. {
  1167. $ip_parts = convertIPv6toInts($fullip);
  1168. $ban_query = '((' . $ip_parts[0] . ' BETWEEN bi.ip_low1 AND bi.ip_high1)
  1169. AND (' . $ip_parts[1] . ' BETWEEN bi.ip_low2 AND bi.ip_high2)
  1170. AND (' . $ip_parts[2] . ' BETWEEN bi.ip_low3 AND bi.ip_high3)
  1171. AND (' . $ip_parts[3] . ' BETWEEN bi.ip_low4 AND bi.ip_high4)
  1172. AND (' . $ip_parts[4] . ' BETWEEN bi.ip_low5 AND bi.ip_high5)
  1173. AND (' . $ip_parts[5] . ' BETWEEN bi.ip_low6 AND bi.ip_high6)
  1174. AND (' . $ip_parts[6] . ' BETWEEN bi.ip_low7 AND bi.ip_high7)
  1175. AND (' . $ip_parts[7] . ' BETWEEN bi.ip_low8 AND bi.ip_high8))';
  1176. }
  1177. // Check if we have a valid IPv4 address.
  1178. elseif (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $fullip, $ip_parts) == 1)
  1179. $ban_query = '((' . $ip_parts[1] . ' BETWEEN bi.ip_low1 AND bi.ip_high1)
  1180. AND (' . $ip_parts[2] . ' BETWEEN bi.ip_low2 AND bi.ip_high2)
  1181. AND (' . $ip_parts[3] . ' BETWEEN bi.ip_low3 AND bi.ip_high3)
  1182. AND (' . $ip_parts[4] . ' BETWEEN bi.ip_low4 AND bi.ip_high4))';
  1183. // We use '255.255.255.255' for 'unknown' since it's not valid anyway.
  1184. else
  1185. $ban_query = '(bi.ip_low1 = 255 AND bi.ip_high1 = 255
  1186. AND bi.ip_low2 = 255 AND bi.ip_high2 = 255
  1187. AND bi.ip_low3 = 255 AND bi.ip_high3 = 255
  1188. AND bi.ip_low4 = 255 AND bi.ip_high4 = 255)';
  1189. return $ban_query;
  1190. }
  1191. /**
  1192. * This sets the X-Frame-Options header.
  1193. *
  1194. * @param string $option the frame option, defaults to deny.
  1195. * @return void.
  1196. * @since 2.1
  1197. */
  1198. function frameOptionsHeader($override = null)
  1199. {
  1200. global $modSettings;
  1201. $option = 'SAMEORIGIN';
  1202. if (is_null($override) && !empty($modSettings['frame_security']))
  1203. $option = $modSettings['frame_security'];
  1204. elseif (in_array($override, array('SAMEORIGIN', 'DENY', 'SAMEORIGIN')))
  1205. $option = $override;
  1206. // Don't bother setting the header if we have disabled it.
  1207. if ($option == 'DISABLE')
  1208. return;
  1209. // Finally set it.
  1210. header('X-Frame-Options: ' . $option);
  1211. // And some other useful ones.
  1212. header('X-XSS-Protection: 1; mode=block');
  1213. header('X-Content-Type-Options: nosniff');
  1214. }
  1215. ?>