Security.php 43 KB

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