Security.php 44 KB

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