Security.php 46 KB

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