Security.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350
  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. $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. 'profile_forum_any', 'profile_other_any', 'profile_signature_any',
  392. 'post_new', 'post_reply_own', 'post_reply_any',
  393. 'delete_own', 'delete_any', 'delete_replies',
  394. 'make_sticky',
  395. 'merge_any', 'split_any',
  396. 'modify_own', 'modify_any', 'modify_replies',
  397. 'move_any',
  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. if (isset($_SESSION['rmc']) && $_SESSION['rmc']['time'] > $modSettings['last_mod_report_action'] && $_SESSION['rmc']['id'] == $user_info['id'])
  445. $contexct['open_member_reports'] = $_SESSION['rmc']['reports'];
  446. elseif (allowedTo('moderate_forum'))
  447. {
  448. require_once($sourcedir . '/ModerationCenter.php');
  449. recountOpenMemberReports();
  450. }
  451. else
  452. $context['open_member_reports'] = 0;
  453. }
  454. /**
  455. * Log a ban in the database.
  456. * Log the current user in the ban logs.
  457. * Increment the hit counters for the specified ban ID's (if any.)
  458. *
  459. * @param array $ban_ids = array()
  460. * @param string $email = null
  461. */
  462. function log_ban($ban_ids = array(), $email = null)
  463. {
  464. global $user_info, $smcFunc;
  465. // Don't log web accelerators, it's very confusing...
  466. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  467. return;
  468. $smcFunc['db_insert']('',
  469. '{db_prefix}log_banned',
  470. array('id_member' => 'int', 'ip' => 'string-16', 'email' => 'string', 'log_time' => 'int'),
  471. array($user_info['id'], $user_info['ip'], ($email === null ? ($user_info['is_guest'] ? '' : $user_info['email']) : $email), time()),
  472. array('id_ban_log')
  473. );
  474. // One extra point for these bans.
  475. if (!empty($ban_ids))
  476. $smcFunc['db_query']('', '
  477. UPDATE {db_prefix}ban_items
  478. SET hits = hits + 1
  479. WHERE id_ban IN ({array_int:ban_ids})',
  480. array(
  481. 'ban_ids' => $ban_ids,
  482. )
  483. );
  484. }
  485. /**
  486. * Checks if a given email address might be banned.
  487. * Check if a given email is banned.
  488. * Performs an immediate ban if the turns turns out positive.
  489. *
  490. * @param string $email
  491. * @param string $restriction
  492. * @param string $error
  493. */
  494. function isBannedEmail($email, $restriction, $error)
  495. {
  496. global $txt, $smcFunc;
  497. // Can't ban an empty email
  498. if (empty($email) || trim($email) == '')
  499. return;
  500. // Let's start with the bans based on your IP/hostname/memberID...
  501. $ban_ids = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['ids'] : array();
  502. $ban_reason = isset($_SESSION['ban'][$restriction]) ? $_SESSION['ban'][$restriction]['reason'] : '';
  503. // ...and add to that the email address you're trying to register.
  504. $request = $smcFunc['db_query']('', '
  505. SELECT bi.id_ban, bg.' . $restriction . ', bg.cannot_access, bg.reason
  506. FROM {db_prefix}ban_items AS bi
  507. INNER JOIN {db_prefix}ban_groups AS bg ON (bg.id_ban_group = bi.id_ban_group)
  508. WHERE {string:email} LIKE bi.email_address
  509. AND (bg.' . $restriction . ' = {int:cannot_access} OR bg.cannot_access = {int:cannot_access})
  510. AND (bg.expire_time IS NULL OR bg.expire_time >= {int:now})',
  511. array(
  512. 'email' => $email,
  513. 'cannot_access' => 1,
  514. 'now' => time(),
  515. )
  516. );
  517. while ($row = $smcFunc['db_fetch_assoc']($request))
  518. {
  519. if (!empty($row['cannot_access']))
  520. {
  521. $_SESSION['ban']['cannot_access']['ids'][] = $row['id_ban'];
  522. $_SESSION['ban']['cannot_access']['reason'] = $row['reason'];
  523. }
  524. if (!empty($row[$restriction]))
  525. {
  526. $ban_ids[] = $row['id_ban'];
  527. $ban_reason = $row['reason'];
  528. }
  529. }
  530. $smcFunc['db_free_result']($request);
  531. // You're in biiig trouble. Banned for the rest of this session!
  532. if (isset($_SESSION['ban']['cannot_access']))
  533. {
  534. log_ban($_SESSION['ban']['cannot_access']['ids']);
  535. $_SESSION['ban']['last_checked'] = time();
  536. fatal_error(sprintf($txt['your_ban'], $txt['guest_title']) . $_SESSION['ban']['cannot_access']['reason'], false);
  537. }
  538. if (!empty($ban_ids))
  539. {
  540. // Log this ban for future reference.
  541. log_ban($ban_ids, $email);
  542. fatal_error($error . $ban_reason, false);
  543. }
  544. }
  545. /**
  546. * Make sure the user's correct session was passed, and they came from here.
  547. * Checks the current session, verifying that the person is who he or she should be.
  548. * Also checks the referrer to make sure they didn't get sent here.
  549. * Depends on the disableCheckUA setting, which is usually missing.
  550. * Will check GET, POST, or REQUEST depending on the passed type.
  551. * Also optionally checks the referring action if passed. (note that the referring action must be by GET.)
  552. *
  553. * @param string $type = 'post' (post, get, request)
  554. * @param string $from_action = ''
  555. * @param bool $is_fatal = true
  556. * @return string the error message if is_fatal is false.
  557. */
  558. function checkSession($type = 'post', $from_action = '', $is_fatal = true)
  559. {
  560. global $sc, $modSettings, $boardurl;
  561. // Is it in as $_POST['sc']?
  562. if ($type == 'post')
  563. {
  564. $check = isset($_POST[$_SESSION['session_var']]) ? $_POST[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_POST['sc']) ? $_POST['sc'] : null);
  565. if ($check !== $sc)
  566. $error = 'session_timeout';
  567. }
  568. // How about $_GET['sesc']?
  569. elseif ($type == 'get')
  570. {
  571. $check = isset($_GET[$_SESSION['session_var']]) ? $_GET[$_SESSION['session_var']] : (empty($modSettings['strictSessionCheck']) && isset($_GET['sesc']) ? $_GET['sesc'] : null);
  572. if ($check !== $sc)
  573. $error = 'session_verify_fail';
  574. }
  575. // Or can it be in either?
  576. elseif ($type == 'request')
  577. {
  578. $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)));
  579. if ($check !== $sc)
  580. $error = 'session_verify_fail';
  581. }
  582. // Verify that they aren't changing user agents on us - that could be bad.
  583. if ((!isset($_SESSION['USER_AGENT']) || $_SESSION['USER_AGENT'] != $_SERVER['HTTP_USER_AGENT']) && empty($modSettings['disableCheckUA']))
  584. $error = 'session_verify_fail';
  585. // Make sure a page with session check requirement is not being prefetched.
  586. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  587. {
  588. ob_end_clean();
  589. header('HTTP/1.1 403 Forbidden');
  590. die;
  591. }
  592. // Check the referring site - it should be the same server at least!
  593. if (isset($_SESSION['request_referer']))
  594. $referrer = $_SESSION['request_referer'];
  595. else
  596. $referrer = isset($_SERVER['HTTP_REFERER']) ? @parse_url($_SERVER['HTTP_REFERER']) : array();
  597. if (!empty($referrer['host']))
  598. {
  599. if (strpos($_SERVER['HTTP_HOST'], ':') !== false)
  600. $real_host = substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], ':'));
  601. else
  602. $real_host = $_SERVER['HTTP_HOST'];
  603. $parsed_url = parse_url($boardurl);
  604. // Are global cookies on? If so, let's check them ;).
  605. if (!empty($modSettings['globalCookies']))
  606. {
  607. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  608. $parsed_url['host'] = $parts[1];
  609. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $referrer['host'], $parts) == 1)
  610. $referrer['host'] = $parts[1];
  611. if (preg_match('~(?:[^\.]+\.)?([^\.]{3,}\..+)\z~i', $real_host, $parts) == 1)
  612. $real_host = $parts[1];
  613. }
  614. // Okay: referrer must either match parsed_url or real_host.
  615. if (isset($parsed_url['host']) && strtolower($referrer['host']) != strtolower($parsed_url['host']) && strtolower($referrer['host']) != strtolower($real_host))
  616. {
  617. $error = 'verify_url_fail';
  618. $log_error = true;
  619. }
  620. }
  621. // Well, first of all, if a from_action is specified you'd better have an old_url.
  622. if (!empty($from_action) && (!isset($_SESSION['old_url']) || preg_match('~[?;&]action=' . $from_action . '([;&]|$)~', $_SESSION['old_url']) == 0))
  623. {
  624. $error = 'verify_url_fail';
  625. $log_error = true;
  626. }
  627. if (strtolower($_SERVER['HTTP_USER_AGENT']) == 'hacker')
  628. fatal_error('Sound the alarm! It\'s a hacker! Close the castle gates!!', false);
  629. // Everything is ok, return an empty string.
  630. if (!isset($error))
  631. return '';
  632. // A session error occurred, show the error.
  633. elseif ($is_fatal)
  634. {
  635. if (isset($_GET['xml']))
  636. {
  637. ob_end_clean();
  638. header('HTTP/1.1 403 Forbidden - Session timeout');
  639. die;
  640. }
  641. else
  642. fatal_lang_error($error, isset($log_error) ? 'user' : false);
  643. }
  644. // A session error occurred, return the error to the calling function.
  645. else
  646. return $error;
  647. // We really should never fall through here, for very important reasons. Let's make sure.
  648. trigger_error('Hacking attempt...', E_USER_ERROR);
  649. }
  650. /**
  651. * Check if a specific confirm parameter was given.
  652. *
  653. * @param string $action
  654. */
  655. function checkConfirm($action)
  656. {
  657. global $modSettings;
  658. if (isset($_GET['confirm']) && isset($_SESSION['confirm_' . $action]) && md5($_GET['confirm'] . $_SERVER['HTTP_USER_AGENT']) == $_SESSION['confirm_' . $action])
  659. return true;
  660. else
  661. {
  662. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed']);
  663. $_SESSION['confirm_' . $action] = md5($token . $_SERVER['HTTP_USER_AGENT']);
  664. return $token;
  665. }
  666. }
  667. /**
  668. * Lets give you a token of our appreciation.
  669. *
  670. * @param string $action
  671. * @param string $type = 'post'
  672. * @return array
  673. */
  674. function createToken($action, $type = 'post')
  675. {
  676. global $modSettings, $context;
  677. $token = md5(mt_rand() . session_id() . (string) microtime() . $modSettings['rand_seed'] . $type);
  678. $token_var = substr(preg_replace('~^\d+~', '', md5(mt_rand() . (string) microtime() . mt_rand())), 0, rand(7, 12));
  679. $_SESSION['token'][$type . '-' . $action] = array($token_var, md5($token . $_SERVER['HTTP_USER_AGENT']), time(), $token);
  680. $context[$action . '_token'] = $token;
  681. $context[$action . '_token_var'] = $token_var;
  682. return array($action . '_token_var' => $token_var, $action . '_token' => $token);
  683. }
  684. /**
  685. * Only patrons with valid tokens can ride this ride.
  686. *
  687. * @param string $action
  688. * @param string $type = 'post' (get, request, or post)
  689. * @param bool $reset = true
  690. * @return boolean
  691. */
  692. function validateToken($action, $type = 'post', $reset = true)
  693. {
  694. $type = $type == 'get' || $type == 'request' ? $type : 'post';
  695. // Logins are special: the token is used to has the password with javascript before POST it
  696. if ($action == 'login')
  697. {
  698. if (isset($_SESSION['token'][$type . '-' . $action]))
  699. {
  700. $return = $_SESSION['token'][$type . '-' . $action][3];
  701. unset($_SESSION['token'][$type . '-' . $action]);
  702. return $return;
  703. }
  704. else
  705. return '';
  706. }
  707. // This nasty piece of code validates a token.
  708. /*
  709. 1. The token exists in session.
  710. 2. The {$type} variable should exist.
  711. 3. We concat the variable we received with the user agent
  712. 4. Match that result against what is in the session.
  713. 5. If it matchs, success, otherwise we fallout.
  714. */
  715. 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])
  716. {
  717. // Invalidate this token now.
  718. unset($_SESSION['token'][$type . '-' . $action]);
  719. return true;
  720. }
  721. // Patrons with invalid tokens get the boot.
  722. if ($reset)
  723. {
  724. // Might as well do some cleanup on this.
  725. cleanTokens();
  726. // I'm back baby.
  727. createToken($action, $type);
  728. fatal_lang_error('token_verify_fail', false);
  729. }
  730. // Remove this token as its useless
  731. else
  732. unset($_SESSION['token'][$type . '-' . $action]);
  733. // Randomly check if we should remove some older tokens.
  734. if (mt_rand(0, 138) == 23)
  735. cleanTokens();
  736. return false;
  737. }
  738. /**
  739. * Removes old unused tokens from session
  740. * defaults to 3 hours before a token is considered expired
  741. * if $complete = true will remove all tokens
  742. *
  743. * @param bool $complete = false
  744. */
  745. function cleanTokens($complete = false)
  746. {
  747. // We appreciate cleaning up after yourselves.
  748. if (!isset($_SESSION['token']))
  749. return;
  750. // Clean up tokens, trying to give enough time still.
  751. foreach ($_SESSION['token'] as $key => $data)
  752. if ($data[2] + 10800 < time() || $complete)
  753. unset($_SESSION['token'][$key]);
  754. }
  755. /**
  756. * Check whether a form has been submitted twice.
  757. * Registers a sequence number for a form.
  758. * Checks whether a submitted sequence number is registered in the current session.
  759. * Depending on the value of is_fatal shows an error or returns true or false.
  760. * Frees a sequence number from the stack after it's been checked.
  761. * Frees a sequence number without checking if action == 'free'.
  762. *
  763. * @param string $action
  764. * @param bool $is_fatal = true
  765. * @return boolean
  766. */
  767. function checkSubmitOnce($action, $is_fatal = true)
  768. {
  769. global $context;
  770. if (!isset($_SESSION['forms']))
  771. $_SESSION['forms'] = array();
  772. // Register a form number and store it in the session stack. (use this on the page that has the form.)
  773. if ($action == 'register')
  774. {
  775. $context['form_sequence_number'] = 0;
  776. while (empty($context['form_sequence_number']) || in_array($context['form_sequence_number'], $_SESSION['forms']))
  777. $context['form_sequence_number'] = mt_rand(1, 16000000);
  778. }
  779. // Check whether the submitted number can be found in the session.
  780. elseif ($action == 'check')
  781. {
  782. if (!isset($_REQUEST['seqnum']))
  783. return true;
  784. elseif (!in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  785. {
  786. $_SESSION['forms'][] = (int) $_REQUEST['seqnum'];
  787. return true;
  788. }
  789. elseif ($is_fatal)
  790. fatal_lang_error('error_form_already_submitted', false);
  791. else
  792. return false;
  793. }
  794. // Don't check, just free the stack number.
  795. elseif ($action == 'free' && isset($_REQUEST['seqnum']) && in_array($_REQUEST['seqnum'], $_SESSION['forms']))
  796. $_SESSION['forms'] = array_diff($_SESSION['forms'], array($_REQUEST['seqnum']));
  797. elseif ($action != 'free')
  798. trigger_error('checkSubmitOnce(): Invalid action \'' . $action . '\'', E_USER_WARNING);
  799. }
  800. /**
  801. * Check the user's permissions.
  802. * checks whether the user is allowed to do permission. (ie. post_new.)
  803. * If boards is specified, checks those boards instead of the current one.
  804. * Always returns true if the user is an administrator.
  805. *
  806. * @param string $permission
  807. * @param array $boards = null
  808. * @return boolean if the user can do the permission
  809. */
  810. function allowedTo($permission, $boards = null)
  811. {
  812. global $user_info, $smcFunc;
  813. // You're always allowed to do nothing. (unless you're a working man, MR. LAZY :P!)
  814. if (empty($permission))
  815. return true;
  816. // You're never allowed to do something if your data hasn't been loaded yet!
  817. if (empty($user_info))
  818. return false;
  819. // Administrators are supermen :P.
  820. if ($user_info['is_admin'])
  821. return true;
  822. // Are we checking the _current_ board, or some other boards?
  823. if ($boards === null)
  824. {
  825. // Check if they can do it.
  826. if (!is_array($permission) && in_array($permission, $user_info['permissions']))
  827. return true;
  828. // Search for any of a list of permissions.
  829. elseif (is_array($permission) && count(array_intersect($permission, $user_info['permissions'])) != 0)
  830. return true;
  831. // You aren't allowed, by default.
  832. else
  833. return false;
  834. }
  835. elseif (!is_array($boards))
  836. $boards = array($boards);
  837. $request = $smcFunc['db_query']('', '
  838. SELECT MIN(bp.add_deny) AS add_deny
  839. FROM {db_prefix}boards AS b
  840. INNER JOIN {db_prefix}board_permissions AS bp ON (bp.id_profile = b.id_profile)
  841. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  842. LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND b.id_group IN ({array_int:group_list})
  843. WHERE b.id_board IN ({array_int:board_list})
  844. AND bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  845. AND bp.permission {raw:permission_list}
  846. AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})
  847. GROUP BY b.id_board',
  848. array(
  849. 'current_member' => $user_info['id'],
  850. 'board_list' => $boards,
  851. 'group_list' => $user_info['groups'],
  852. 'moderator_group' => 3,
  853. 'permission_list' => (is_array($permission) ? 'IN (\'' . implode('\', \'', $permission) . '\')' : ' = \'' . $permission . '\''),
  854. )
  855. );
  856. // Make sure they can do it on all of the boards.
  857. if ($smcFunc['db_num_rows']($request) != count($boards))
  858. return false;
  859. $result = true;
  860. while ($row = $smcFunc['db_fetch_assoc']($request))
  861. $result &= !empty($row['add_deny']);
  862. $smcFunc['db_free_result']($request);
  863. // If the query returned 1, they can do it... otherwise, they can't.
  864. return $result;
  865. }
  866. /**
  867. * Fatal error if they cannot.
  868. * Uses allowedTo() to check if the user is allowed to do permission.
  869. * Checks the passed boards or current board for the permission.
  870. * If they are not, it loads the Errors language file and shows an error using $txt['cannot_' . $permission].
  871. * If they are a guest and cannot do it, this calls is_not_guest().
  872. *
  873. * @param string $permission
  874. * @param array $boards = null
  875. */
  876. function isAllowedTo($permission, $boards = null)
  877. {
  878. global $user_info, $txt;
  879. static $heavy_permissions = array(
  880. 'admin_forum',
  881. 'manage_attachments',
  882. 'manage_smileys',
  883. 'manage_boards',
  884. 'edit_news',
  885. 'moderate_forum',
  886. 'manage_bans',
  887. 'manage_membergroups',
  888. 'manage_permissions',
  889. );
  890. // Make it an array, even if a string was passed.
  891. $permission = is_array($permission) ? $permission : array($permission);
  892. // Check the permission and return an error...
  893. if (!allowedTo($permission, $boards))
  894. {
  895. // Pick the last array entry as the permission shown as the error.
  896. $error_permission = array_shift($permission);
  897. // If they are a guest, show a login. (because the error might be gone if they do!)
  898. if ($user_info['is_guest'])
  899. {
  900. loadLanguage('Errors');
  901. is_not_guest($txt['cannot_' . $error_permission]);
  902. }
  903. // Clear the action because they aren't really doing that!
  904. $_GET['action'] = '';
  905. $_GET['board'] = '';
  906. $_GET['topic'] = '';
  907. writeLog(true);
  908. fatal_lang_error('cannot_' . $error_permission, false);
  909. // Getting this far is a really big problem, but let's try our best to prevent any cases...
  910. trigger_error('Hacking attempt...', E_USER_ERROR);
  911. }
  912. // If you're doing something on behalf of some "heavy" permissions, validate your session.
  913. // (take out the heavy permissions, and if you can't do anything but those, you need a validated session.)
  914. if (!allowedTo(array_diff($permission, $heavy_permissions), $boards))
  915. validateSession();
  916. }
  917. /**
  918. * Return the boards a user has a certain (board) permission on. (array(0) if all.)
  919. * - returns a list of boards on which the user is allowed to do the specified permission.
  920. * - returns an array with only a 0 in it if the user has permission to do this on every board.
  921. * - returns an empty array if he or she cannot do this on any board.
  922. * If check_access is true will also make sure the group has proper access to that board.
  923. *
  924. * @param array $permissions
  925. * @param bool $check_access = true
  926. * @param bool $simple = true
  927. */
  928. function boardsAllowedTo($permissions, $check_access = true, $simple = true)
  929. {
  930. global $user_info, $smcFunc;
  931. // Arrays are nice, most of the time.
  932. if (!is_array($permissions))
  933. $permissions = array($permissions);
  934. /*
  935. * Set $simple to true to use this function as it were in SMF 2.0.x.
  936. * Otherwise, the resultant array becomes split into the multiple
  937. * permissions that were passed. Other than that, it's just the normal
  938. * state of play that you're used to.
  939. */
  940. // Administrators are all powerful, sorry.
  941. if ($user_info['is_admin'])
  942. {
  943. if ($simple)
  944. return array(0);
  945. else
  946. {
  947. $boards = array();
  948. foreach ($permissions as $permission)
  949. $boards[$permission] = array(0);
  950. return $boards;
  951. }
  952. }
  953. // All groups the user is in except 'moderator'.
  954. $groups = array_diff($user_info['groups'], array(3));
  955. $request = $smcFunc['db_query']('', '
  956. SELECT b.id_board, bp.add_deny' . ($simple ? '' : ', bp.permission') . '
  957. FROM {db_prefix}board_permissions AS bp
  958. INNER JOIN {db_prefix}boards AS b ON (b.id_profile = bp.id_profile)
  959. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = b.id_board AND mods.id_member = {int:current_member})
  960. LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = b.id_board AND modgs.id_group IN ({array_int:group_list}))
  961. WHERE bp.id_group IN ({array_int:group_list}, {int:moderator_group})
  962. AND bp.permission IN ({array_string:permissions})
  963. AND (mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR bp.id_group != {int:moderator_group})' .
  964. ($check_access ? ' AND {query_see_board}' : ''),
  965. array(
  966. 'current_member' => $user_info['id'],
  967. 'group_list' => $groups,
  968. 'moderator_group' => 3,
  969. 'permissions' => $permissions,
  970. )
  971. );
  972. $boards = array();
  973. $deny_boards = array();
  974. while ($row = $smcFunc['db_fetch_assoc']($request))
  975. {
  976. if ($simple)
  977. {
  978. if (empty($row['add_deny']))
  979. $deny_boards[] = $row['id_board'];
  980. else
  981. $boards[] = $row['id_board'];
  982. }
  983. else
  984. {
  985. if (empty($row['add_deny']))
  986. $deny_boards[$row['permission']][] = $row['id_board'];
  987. else
  988. $boards[$row['permission']][] = $row['id_board'];
  989. }
  990. }
  991. $smcFunc['db_free_result']($request);
  992. if ($simple)
  993. $boards = array_unique(array_values(array_diff($boards, $deny_boards)));
  994. else
  995. {
  996. foreach ($permissions as $permission)
  997. {
  998. // never had it to start with
  999. if (empty($boards[$permission]))
  1000. $boards[$permission] = array();
  1001. else
  1002. {
  1003. // Or it may have been removed
  1004. $deny_boards[$permission] = isset($deny_boards[$permission]) ? $deny_boards[$permission] : array();
  1005. $boards[$permission] = array_unique(array_values(array_diff($boards[$permission], $deny_boards[$permission])));
  1006. }
  1007. }
  1008. }
  1009. return $boards;
  1010. }
  1011. /**
  1012. * This function attempts to protect from spammed messages and the like.
  1013. * The time taken depends on error_type - generally uses the modSetting.
  1014. *
  1015. * @param string $error_type used also as a $txt index. (not an actual string.)
  1016. * @return boolean
  1017. */
  1018. function spamProtection($error_type)
  1019. {
  1020. global $modSettings, $user_info, $smcFunc;
  1021. // Certain types take less/more time.
  1022. $timeOverrides = array(
  1023. 'login' => 2,
  1024. 'register' => 2,
  1025. 'remind' => 30,
  1026. 'sendmail' => $modSettings['spamWaitTime'] * 5,
  1027. 'reporttm' => $modSettings['spamWaitTime'] * 4,
  1028. 'search' => !empty($modSettings['search_floodcontrol_time']) ? $modSettings['search_floodcontrol_time'] : 1,
  1029. );
  1030. call_integration_hook('integrate_spam_protection', array(&$timeOverrides));
  1031. // Moderators are free...
  1032. if (!allowedTo('moderate_board'))
  1033. $timeLimit = isset($timeOverrides[$error_type]) ? $timeOverrides[$error_type] : $modSettings['spamWaitTime'];
  1034. else
  1035. $timeLimit = 2;
  1036. // Delete old entries...
  1037. $smcFunc['db_query']('', '
  1038. DELETE FROM {db_prefix}log_floodcontrol
  1039. WHERE log_time < {int:log_time}
  1040. AND log_type = {string:log_type}',
  1041. array(
  1042. 'log_time' => time() - $timeLimit,
  1043. 'log_type' => $error_type,
  1044. )
  1045. );
  1046. // Add a new entry, deleting the old if necessary.
  1047. $smcFunc['db_insert']('replace',
  1048. '{db_prefix}log_floodcontrol',
  1049. array('ip' => 'string-16', 'log_time' => 'int', 'log_type' => 'string'),
  1050. array($user_info['ip'], time(), $error_type),
  1051. array('ip', 'log_type')
  1052. );
  1053. // If affected is 0 or 2, it was there already.
  1054. if ($smcFunc['db_affected_rows']() != 1)
  1055. {
  1056. // Spammer! You only have to wait a *few* seconds!
  1057. fatal_lang_error($error_type . '_WaitTime_broken', false, array($timeLimit));
  1058. return true;
  1059. }
  1060. // They haven't posted within the limit.
  1061. return false;
  1062. }
  1063. /**
  1064. * A generic function to create a pair of index.php and .htaccess files in a directory
  1065. *
  1066. * @param string $path the (absolute) directory path
  1067. * @param boolean $attachments if the directory is an attachments directory or not
  1068. * @return true on success error string if anything fails
  1069. */
  1070. function secureDirectory($path, $attachments = false)
  1071. {
  1072. if (empty($path))
  1073. return 'empty_path';
  1074. if (!is_writable($path))
  1075. return 'path_not_writable';
  1076. $directoryname = basename($path);
  1077. $errors = array();
  1078. $close = empty($attachments) ? '
  1079. </Files>' : '
  1080. Allow from localhost
  1081. </Files>
  1082. RemoveHandler .php .php3 .phtml .cgi .fcgi .pl .fpl .shtml';
  1083. if (file_exists($path . '/.htaccess'))
  1084. $errors[] = 'htaccess_exists';
  1085. else
  1086. {
  1087. $fh = @fopen($path . '/.htaccess', 'w');
  1088. if ($fh) {
  1089. fwrite($fh, '<Files *>
  1090. Order Deny,Allow
  1091. Deny from all' . $close);
  1092. fclose($fh);
  1093. }
  1094. $errors[] = 'htaccess_cannot_create_file';
  1095. }
  1096. if (file_exists($path . '/index.php'))
  1097. $errors[] = 'index-php_exists';
  1098. else
  1099. {
  1100. $fh = @fopen($path . '/index.php', 'w');
  1101. if ($fh) {
  1102. fwrite($fh, '<' . '?php
  1103. /**
  1104. * This file is here solely to protect your ' . $directoryname . ' directory.
  1105. */
  1106. // Look for Settings.php....
  1107. if (file_exists(dirname(dirname(__FILE__)) . \'/Settings.php\'))
  1108. {
  1109. // Found it!
  1110. require(dirname(dirname(__FILE__)) . \'/Settings.php\');
  1111. header(\'Location: \' . $boardurl);
  1112. }
  1113. // Can\'t find it... just forget it.
  1114. else
  1115. exit;
  1116. ?'. '>');
  1117. fclose($fh);
  1118. }
  1119. $errors[] = 'index-php_cannot_create_file';
  1120. }
  1121. if (!empty($errors))
  1122. return $errors;
  1123. else
  1124. return true;
  1125. }
  1126. /**
  1127. * Helper function that puts together a ban query for a given ip
  1128. * builds the query for ipv6, ipv4 or 255.255.255.255 depending on whats supplied
  1129. *
  1130. * @param string $fullip An IP address either IPv6 or not
  1131. * @return string A SQL condition
  1132. */
  1133. function constructBanQueryIP($fullip)
  1134. {
  1135. // First attempt a IPv6 address.
  1136. if (isValidIPv6($fullip))
  1137. {
  1138. $ip_parts = convertIPv6toInts($fullip);
  1139. $ban_query = '((' . $ip_parts[0] . ' BETWEEN bi.ip_low1 AND bi.ip_high1)
  1140. AND (' . $ip_parts[1] . ' BETWEEN bi.ip_low2 AND bi.ip_high2)
  1141. AND (' . $ip_parts[2] . ' BETWEEN bi.ip_low3 AND bi.ip_high3)
  1142. AND (' . $ip_parts[3] . ' BETWEEN bi.ip_low4 AND bi.ip_high4)
  1143. AND (' . $ip_parts[4] . ' BETWEEN bi.ip_low5 AND bi.ip_high5)
  1144. AND (' . $ip_parts[5] . ' BETWEEN bi.ip_low6 AND bi.ip_high6)
  1145. AND (' . $ip_parts[6] . ' BETWEEN bi.ip_low7 AND bi.ip_high7)
  1146. AND (' . $ip_parts[7] . ' BETWEEN bi.ip_low8 AND bi.ip_high8))';
  1147. }
  1148. // Check if we have a valid IPv4 address.
  1149. elseif (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $fullip, $ip_parts) == 1)
  1150. $ban_query = '((' . $ip_parts[1] . ' BETWEEN bi.ip_low1 AND bi.ip_high1)
  1151. AND (' . $ip_parts[2] . ' BETWEEN bi.ip_low2 AND bi.ip_high2)
  1152. AND (' . $ip_parts[3] . ' BETWEEN bi.ip_low3 AND bi.ip_high3)
  1153. AND (' . $ip_parts[4] . ' BETWEEN bi.ip_low4 AND bi.ip_high4))';
  1154. // We use '255.255.255.255' for 'unknown' since it's not valid anyway.
  1155. else
  1156. $ban_query = '(bi.ip_low1 = 255 AND bi.ip_high1 = 255
  1157. AND bi.ip_low2 = 255 AND bi.ip_high2 = 255
  1158. AND bi.ip_low3 = 255 AND bi.ip_high3 = 255
  1159. AND bi.ip_low4 = 255 AND bi.ip_high4 = 255)';
  1160. return $ban_query;
  1161. }
  1162. /**
  1163. * This sets the X-Frame-Options header.
  1164. *
  1165. * @param string $option the frame option, defaults to deny.
  1166. * @return void.
  1167. * @since 2.1
  1168. */
  1169. function frameOptionsHeader($override = null)
  1170. {
  1171. global $modSettings;
  1172. $option = 'SAMEORIGIN';
  1173. if (is_null($override) && !empty($modSettings['frame_security']))
  1174. $option = $modSettings['frame_security'];
  1175. elseif (in_array($override, array('SAMEORIGIN', 'DENY', 'SAMEORIGIN')))
  1176. $option = $override;
  1177. // Don't bother setting the header if we have disabled it.
  1178. if ($option == 'DISABLE')
  1179. return;
  1180. // Finally set it.
  1181. header('X-Frame-Options: ' . $option);
  1182. // And some other useful ones.
  1183. header('X-XSS-Protection: 1');
  1184. header('X-Content-Type-Options: nosniff');
  1185. }
  1186. ?>