Security.php 45 KB

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