Subs-Auth.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. <?php
  2. /**
  3. * This file has functions in it to do with authentication, user handling, and the like.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2011 Simple Machines
  10. * @license http://www.simplemachines.org/about/smf/license.php BSD
  11. *
  12. * @version 2.1 Alpha 1
  13. */
  14. if (!defined('SMF'))
  15. die('Hacking attempt...');
  16. /**
  17. * sets the SMF-style login cookie and session based on the id_member and password passed.
  18. * password should be already encrypted with the cookie salt.
  19. * logs the user out if id_member is zero.
  20. * sets the cookie and session to last the number of seconds specified by cookie_length.
  21. * when logging out, if the globalCookies setting is enabled, attempts to clear the subdomain's cookie too.
  22. * @param int $cookie_length,
  23. * @param int $id The id of the member
  24. * @param string $password = ''
  25. */
  26. function setLoginCookie($cookie_length, $id, $password = '')
  27. {
  28. global $cookiename, $boardurl, $modSettings, $sourcedir;
  29. // If changing state force them to re-address some permission caching.
  30. $_SESSION['mc']['time'] = 0;
  31. // The cookie may already exist, and have been set with different options.
  32. $cookie_state = (empty($modSettings['localCookies']) ? 0 : 1) | (empty($modSettings['globalCookies']) ? 0 : 2);
  33. if (isset($_COOKIE[$cookiename]) && preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~', $_COOKIE[$cookiename]) === 1)
  34. {
  35. $array = @unserialize($_COOKIE[$cookiename]);
  36. // Out with the old, in with the new!
  37. if (isset($array[3]) && $array[3] != $cookie_state)
  38. {
  39. $cookie_url = url_parts($array[3] & 1 > 0, $array[3] & 2 > 0);
  40. setcookie($cookiename, serialize(array(0, '', 0)), time() - 3600, $cookie_url[1], $cookie_url[0], !empty($modSettings['secureCookies']));
  41. }
  42. }
  43. // Get the data and path to set it on.
  44. $data = serialize(empty($id) ? array(0, '', 0) : array($id, $password, time() + $cookie_length, $cookie_state));
  45. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  46. // Set the cookie, $_COOKIE, and session variable.
  47. setcookie($cookiename, $data, time() + $cookie_length, $cookie_url[1], $cookie_url[0], !empty($modSettings['secureCookies']));
  48. // If subdomain-independent cookies are on, unset the subdomain-dependent cookie too.
  49. if (empty($id) && !empty($modSettings['globalCookies']))
  50. setcookie($cookiename, $data, time() + $cookie_length, $cookie_url[1], '', !empty($modSettings['secureCookies']));
  51. // Any alias URLs? This is mainly for use with frames, etc.
  52. if (!empty($modSettings['forum_alias_urls']))
  53. {
  54. $aliases = explode(',', $modSettings['forum_alias_urls']);
  55. $temp = $boardurl;
  56. foreach ($aliases as $alias)
  57. {
  58. // Fake the $boardurl so we can set a different cookie.
  59. $alias = strtr(trim($alias), array('http://' => '', 'https://' => ''));
  60. $boardurl = 'http://' . $alias;
  61. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  62. if ($cookie_url[0] == '')
  63. $cookie_url[0] = strtok($alias, '/');
  64. setcookie($cookiename, $data, time() + $cookie_length, $cookie_url[1], $cookie_url[0], !empty($modSettings['secureCookies']));
  65. }
  66. $boardurl = $temp;
  67. }
  68. $_COOKIE[$cookiename] = $data;
  69. // Make sure the user logs in with a new session ID.
  70. if (!isset($_SESSION['login_' . $cookiename]) || $_SESSION['login_' . $cookiename] !== $data)
  71. {
  72. // We need to meddle with the session.
  73. require_once($sourcedir . '/Session.php');
  74. // Backup and remove the old session.
  75. $oldSessionData = $_SESSION;
  76. $_SESSION = array();
  77. session_destroy();
  78. // Recreate and restore the new session.
  79. loadSession();
  80. session_regenerate_id();
  81. $_SESSION = $oldSessionData;
  82. // Version 4.3.2 didn't store the cookie of the new session.
  83. if (version_compare(PHP_VERSION, '4.3.2', '==') || !isset($_COOKIE[session_name()]) || $_COOKIE[session_name()] != session_id())
  84. {
  85. $sessionCookieLifetime = ini_get('session.cookie_lifetime');
  86. setcookie(session_name(), session_id(), time() + (empty($sessionCookieLifetime) ? $cookie_length : $sessionCookieLifetime), $cookie_url[1], $cookie_url[0], !empty($modSettings['secureCookies']));
  87. }
  88. $_SESSION['login_' . $cookiename] = $data;
  89. }
  90. }
  91. // @todo remove this? wouldn't it get caught earlier?
  92. // PHP < 4.3.2 doesn't have this function
  93. if (!function_exists('session_regenerate_id'))
  94. {
  95. require_once $sourcedir . 'Subs-Compat.php';
  96. }
  97. /**
  98. * Get the domain and path for the cookie
  99. * normally, local and global should be the localCookies and globalCookies settings, respectively.
  100. * uses boardurl to determine these two things.
  101. * @param bool $local,
  102. * @param bool $global
  103. * @return array an array to set the cookie on with domain and path in it, in that order
  104. */
  105. function url_parts($local, $global)
  106. {
  107. global $boardurl;
  108. // Parse the URL with PHP to make life easier.
  109. $parsed_url = parse_url($boardurl);
  110. // Is local cookies off?
  111. if (empty($parsed_url['path']) || !$local)
  112. $parsed_url['path'] = '';
  113. // Globalize cookies across domains (filter out IP-addresses)?
  114. if ($global && preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $parsed_url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  115. $parsed_url['host'] = '.' . $parts[1];
  116. // We shouldn't use a host at all if both options are off.
  117. elseif (!$local && !$global)
  118. $parsed_url['host'] = '';
  119. // The host also shouldn't be set if there aren't any dots in it.
  120. elseif (!isset($parsed_url['host']) || strpos($parsed_url['host'], '.') === false)
  121. $parsed_url['host'] = '';
  122. return array($parsed_url['host'], $parsed_url['path'] . '/');
  123. }
  124. /**
  125. * Throws guests out to the login screen when guest access is off.
  126. * sets $_SESSION['login_url'] to $_SERVER['REQUEST_URL'].
  127. * uses the 'kick_guest' sub template found in Login.template.php.
  128. */
  129. function KickGuest()
  130. {
  131. global $txt, $context;
  132. loadLanguage('Login');
  133. loadTemplate('Login');
  134. // Never redirect to an attachment
  135. if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
  136. $_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
  137. $context['sub_template'] = 'kick_guest';
  138. $context['page_title'] = $txt['login'];
  139. }
  140. /**
  141. * Display a message about being in maintenance mode.
  142. * display a login screen with sub template 'maintenance'.
  143. */
  144. function InMaintenance()
  145. {
  146. global $txt, $mtitle, $mmessage, $context;
  147. loadLanguage('Login');
  148. loadTemplate('Login');
  149. // Send a 503 header, so search engines don't bother indexing while we're in maintenance mode.
  150. header('HTTP/1.1 503 Service Temporarily Unavailable');
  151. // Basic template stuff..
  152. $context['sub_template'] = 'maintenance';
  153. $context['title'] = &$mtitle;
  154. $context['description'] = &$mmessage;
  155. $context['page_title'] = $txt['maintain_mode'];
  156. }
  157. /**
  158. * Double check the verity of the admin by asking for his or her password.
  159. * loads Login.template.php and uses the admin_login sub template.
  160. * sends data to template so the admin is sent on to the page they
  161. * wanted if their password is correct, otherwise they can try again.
  162. * @param string $type = 'admin'
  163. */
  164. function adminLogin($type = 'admin')
  165. {
  166. global $context, $scripturl, $txt, $user_info, $user_settings;
  167. loadLanguage('Admin');
  168. loadTemplate('Login');
  169. // Validate what type of session check this is.
  170. $types = array();
  171. call_integration_hook('integrate_validateSession', array($types));
  172. $type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';
  173. // They used a wrong password, log it and unset that.
  174. if (isset($_POST[$type . '_hash_pass']) || isset($_POST[$type . '_pass']))
  175. {
  176. $txt['security_wrong'] = sprintf($txt['security_wrong'], isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $txt['unknown'], $_SERVER['HTTP_USER_AGENT'], $user_info['ip']);
  177. log_error($txt['security_wrong'], 'critical');
  178. if (isset($_POST[$type . '_hash_pass']))
  179. unset($_POST[$type . '_hash_pass']);
  180. if (isset($_POST[$type . '_pass']))
  181. unset($_POST[$type . '_pass']);
  182. $context['incorrect_password'] = true;
  183. }
  184. createToken('admin-login');
  185. // Figure out the get data and post data.
  186. $context['get_data'] = '?' . construct_query_string($_GET);
  187. $context['post_data'] = '';
  188. // Now go through $_POST. Make sure the session hash is sent.
  189. $_POST[$context['session_var']] = $context['session_id'];
  190. foreach ($_POST as $k => $v)
  191. $context['post_data'] .= adminLogin_outputPostVars($k, $v);
  192. // Now we'll use the admin_login sub template of the Login template.
  193. $context['sub_template'] = 'admin_login';
  194. // And title the page something like "Login".
  195. if (!isset($context['page_title']))
  196. $context['page_title'] = $txt['login'];
  197. // The type of action.
  198. $context['sessionCheckType'] = $type;
  199. obExit();
  200. // We MUST exit at this point, because otherwise we CANNOT KNOW that the user is privileged.
  201. trigger_error('Hacking attempt...', E_USER_ERROR);
  202. }
  203. /**
  204. * used by the adminLogin() function.
  205. * if 'value' is an array, the function is called recursively.
  206. * @param string $key
  207. * @param string $value
  208. * @return string 'hidden' HTML form fields, containing key-value-pairs
  209. */
  210. function adminLogin_outputPostVars($k, $v)
  211. {
  212. global $smcFunc;
  213. if (!is_array($v))
  214. return '
  215. <input type="hidden" name="' . htmlspecialchars($k) . '" value="' . strtr($v, array('"' => '&quot;', '<' => '&lt;', '>' => '&gt;')) . '" />';
  216. else
  217. {
  218. $ret = '';
  219. foreach ($v as $k2 => $v2)
  220. $ret .= adminLogin_outputPostVars($k . '[' . $k2 . ']', $v2);
  221. return $ret;
  222. }
  223. }
  224. function construct_query_string($get)
  225. {
  226. global $scripturl;
  227. $query_string = '';
  228. // Awww, darn. The $scripturl contains GET stuff!
  229. $q = strpos($scripturl, '?');
  230. if ($q !== false)
  231. {
  232. parse_str(preg_replace('/&(\w+)(?=&|$)/', '&$1=', strtr(substr($scripturl, $q + 1), ';', '&')), $temp);
  233. foreach ($get as $k => $v)
  234. {
  235. // Only if it's not already in the $scripturl!
  236. if (!isset($temp[$k]))
  237. $query_string .= urlencode($k) . '=' . urlencode($v) . ';';
  238. // If it changed, put it out there, but with an ampersand.
  239. elseif ($temp[$k] != $get[$k])
  240. $query_string .= urlencode($k) . '=' . urlencode($v) . '&amp;';
  241. }
  242. }
  243. else
  244. {
  245. // Add up all the data from $_GET into get_data.
  246. foreach ($get as $k => $v)
  247. $query_string .= urlencode($k) . '=' . urlencode($v) . ';';
  248. }
  249. $query_string = substr($query_string, 0, -1);
  250. return $query_string;
  251. }
  252. // Find members by email address, username, or real name.
  253. /**
  254. * searches for members whose username, display name, or e-mail address match the given pattern of array names.
  255. * searches only buddies if buddies_only is set.
  256. * @param array $names,
  257. * @param bool $use_wildcards = false, accepts wildcards ? and * in the patern if true
  258. * @param bool $buddies_only = false,
  259. * @param int $max = 500 retrieves a maximum of max members, if passed
  260. * @return array containing information about the matching members
  261. */
  262. function findMembers($names, $use_wildcards = false, $buddies_only = false, $max = 500)
  263. {
  264. global $scripturl, $user_info, $modSettings, $smcFunc;
  265. // If it's not already an array, make it one.
  266. if (!is_array($names))
  267. $names = explode(',', $names);
  268. $maybe_email = false;
  269. foreach ($names as $i => $name)
  270. {
  271. // Trim, and fix wildcards for each name.
  272. $names[$i] = trim($smcFunc['strtolower']($name));
  273. $maybe_email |= strpos($name, '@') !== false;
  274. // Make it so standard wildcards will work. (* and ?)
  275. if ($use_wildcards)
  276. $names[$i] = strtr($names[$i], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '\'' => '&#039;'));
  277. else
  278. $names[$i] = strtr($names[$i], array('\'' => '&#039;'));
  279. }
  280. // What are we using to compare?
  281. $comparison = $use_wildcards ? 'LIKE' : '=';
  282. // Nothing found yet.
  283. $results = array();
  284. // This ensures you can't search someones email address if you can't see it.
  285. $email_condition = allowedTo('moderate_forum') ? '' : 'hide_email = 0 AND ';
  286. if ($use_wildcards || $maybe_email)
  287. $email_condition = '
  288. OR (' . $email_condition . 'email_address ' . $comparison . ' \'' . implode( '\') OR (' . $email_condition . ' email_address ' . $comparison . ' \'', $names) . '\')';
  289. else
  290. $email_condition = '';
  291. // Get the case of the columns right - but only if we need to as things like MySQL will go slow needlessly otherwise.
  292. $member_name = $smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name';
  293. $real_name = $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name';
  294. // Search by username, display name, and email address.
  295. $request = $smcFunc['db_query']('', '
  296. SELECT id_member, member_name, real_name, email_address, hide_email
  297. FROM {db_prefix}members
  298. WHERE ({raw:member_name_search}
  299. OR {raw:real_name_search} {raw:email_condition})
  300. ' . ($buddies_only ? 'AND id_member IN ({array_int:buddy_list})' : '') . '
  301. AND is_activated IN (1, 11)
  302. LIMIT {int:limit}',
  303. array(
  304. 'buddy_list' => $user_info['buddies'],
  305. 'member_name_search' => $member_name . ' ' . $comparison . ' \'' . implode( '\' OR ' . $member_name . ' ' . $comparison . ' \'', $names) . '\'',
  306. 'real_name_search' => $real_name . ' ' . $comparison . ' \'' . implode( '\' OR ' . $real_name . ' ' . $comparison . ' \'', $names) . '\'',
  307. 'email_condition' => $email_condition,
  308. 'limit' => $max,
  309. )
  310. );
  311. while ($row = $smcFunc['db_fetch_assoc']($request))
  312. {
  313. $results[$row['id_member']] = array(
  314. 'id' => $row['id_member'],
  315. 'name' => $row['real_name'],
  316. 'username' => $row['member_name'],
  317. 'email' => in_array(showEmailAddress(!empty($row['hide_email']), $row['id_member']), array('yes', 'yes_permission_override')) ? $row['email_address'] : '',
  318. 'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
  319. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>'
  320. );
  321. }
  322. $smcFunc['db_free_result']($request);
  323. // Return all the results.
  324. return $results;
  325. }
  326. /**
  327. * called by index.php?action=findmember.
  328. * is used as a popup for searching members.
  329. * uses sub template find_members of the Help template.
  330. * also used to add members for PM's sent using wap2/imode protocol.
  331. */
  332. function JSMembers()
  333. {
  334. global $context, $scripturl, $user_info, $smcFunc;
  335. checkSession('get');
  336. if (WIRELESS)
  337. $context['sub_template'] = WIRELESS_PROTOCOL . '_pm';
  338. else
  339. {
  340. // Why is this in the Help template, you ask? Well, erm... it helps you. Does that work?
  341. loadTemplate('Help');
  342. $context['template_layers'] = array();
  343. $context['sub_template'] = 'find_members';
  344. }
  345. if (isset($_REQUEST['search']))
  346. $context['last_search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
  347. else
  348. $_REQUEST['start'] = 0;
  349. // Allow the user to pass the input to be added to to the box.
  350. $context['input_box_name'] = isset($_REQUEST['input']) && preg_match('~^[\w-]+$~', $_REQUEST['input']) === 1 ? $_REQUEST['input'] : 'to';
  351. // Take the delimiter over GET in case it's \n or something.
  352. $context['delimiter'] = isset($_REQUEST['delim']) ? ($_REQUEST['delim'] == 'LB' ? "\n" : $_REQUEST['delim']) : ', ';
  353. $context['quote_results'] = !empty($_REQUEST['quote']);
  354. // List all the results.
  355. $context['results'] = array();
  356. // Some buddy related settings ;)
  357. $context['show_buddies'] = !empty($user_info['buddies']);
  358. $context['buddy_search'] = isset($_REQUEST['buddies']);
  359. // If the user has done a search, well - search.
  360. if (isset($_REQUEST['search']))
  361. {
  362. $_REQUEST['search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
  363. $context['results'] = findMembers(array($_REQUEST['search']), true, $context['buddy_search']);
  364. $total_results = count($context['results']);
  365. $context['page_index'] = constructPageIndex($scripturl . '?action=findmember;search=' . $context['last_search'] . ';' . $context['session_var'] . '=' . $context['session_id'] . ';input=' . $context['input_box_name'] . ($context['quote_results'] ? ';quote=1' : '') . ($context['buddy_search'] ? ';buddies' : ''), $_REQUEST['start'], $total_results, 7);
  366. // Determine the navigation context (especially useful for the wireless template).
  367. $base_url = $scripturl . '?action=findmember;search=' . urlencode($context['last_search']) . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']) . ';' . $context['session_var'] . '=' . $context['session_id'];
  368. $context['links'] = array(
  369. 'first' => $_REQUEST['start'] >= 7 ? $base_url . ';start=0' : '',
  370. 'prev' => $_REQUEST['start'] >= 7 ? $base_url . ';start=' . ($_REQUEST['start'] - 7) : '',
  371. 'next' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . ($_REQUEST['start'] + 7) : '',
  372. 'last' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . (floor(($total_results - 1) / 7) * 7) : '',
  373. 'up' => $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']),
  374. );
  375. $context['page_info'] = array(
  376. 'current_page' => $_REQUEST['start'] / 7 + 1,
  377. 'num_pages' => floor(($total_results - 1) / 7) + 1
  378. );
  379. $context['results'] = array_slice($context['results'], $_REQUEST['start'], 7);
  380. }
  381. else
  382. $context['links']['up'] = $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']);
  383. }
  384. /**
  385. * outputs each member name on its own line.
  386. * used by javascript to find members matching the request.
  387. */
  388. function RequestMembers()
  389. {
  390. global $user_info, $txt, $smcFunc;
  391. checkSession('get');
  392. $_REQUEST['search'] = $smcFunc['htmlspecialchars']($_REQUEST['search']) . '*';
  393. $_REQUEST['search'] = trim($smcFunc['strtolower']($_REQUEST['search']));
  394. $_REQUEST['search'] = strtr($_REQUEST['search'], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&#038;' => '&amp;'));
  395. if (function_exists('iconv'))
  396. header('Content-Type: text/plain; charset=UTF-8');
  397. $request = $smcFunc['db_query']('', '
  398. SELECT real_name
  399. FROM {db_prefix}members
  400. WHERE real_name LIKE {string:search}' . (isset($_REQUEST['buddies']) ? '
  401. AND id_member IN ({array_int:buddy_list})' : '') . '
  402. AND is_activated IN (1, 11)
  403. LIMIT ' . ($smcFunc['strlen']($_REQUEST['search']) <= 2 ? '100' : '800'),
  404. array(
  405. 'buddy_list' => $user_info['buddies'],
  406. 'search' => $_REQUEST['search'],
  407. )
  408. );
  409. while ($row = $smcFunc['db_fetch_assoc']($request))
  410. {
  411. if (function_exists('iconv'))
  412. {
  413. $utf8 = iconv($txt['lang_character_set'], 'UTF-8', $row['real_name']);
  414. if ($utf8)
  415. $row['real_name'] = $utf8;
  416. }
  417. $row['real_name'] = strtr($row['real_name'], array('&amp;' => '&#038;', '&lt;' => '&#060;', '&gt;' => '&#062;', '&quot;' => '&#034;'));
  418. if (preg_match('~&#\d+;~', $row['real_name']) != 0)
  419. {
  420. $fixchar = create_function('$n', '
  421. if ($n < 128)
  422. return chr($n);
  423. elseif ($n < 2048)
  424. return chr(192 | $n >> 6) . chr(128 | $n & 63);
  425. elseif ($n < 65536)
  426. return chr(224 | $n >> 12) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);
  427. else
  428. return chr(240 | $n >> 18) . chr(128 | $n >> 12 & 63) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);');
  429. $row['real_name'] = preg_replace('~&#(\d+);~e', '$fixchar(\'$1\')', $row['real_name']);
  430. }
  431. echo $row['real_name'], "\n";
  432. }
  433. $smcFunc['db_free_result']($request);
  434. obExit(false);
  435. }
  436. /**
  437. * Generates a random password for a user and emails it to them.
  438. * called by Profile.php when changing someone's username.
  439. * checks the validity of the new username.
  440. * generates and sets a new password for the given user.
  441. * mails the new password to the email address of the user.
  442. * if username is not set, only a new password is generated and sent.
  443. * @param int $memID
  444. * @param string $username = null
  445. */
  446. function resetPassword($memID, $username = null)
  447. {
  448. global $scripturl, $context, $txt, $sourcedir, $modSettings, $smcFunc, $language;
  449. // Language... and a required file.
  450. loadLanguage('Login');
  451. require_once($sourcedir . '/Subs-Post.php');
  452. // Get some important details.
  453. $request = $smcFunc['db_query']('', '
  454. SELECT member_name, email_address, lngfile
  455. FROM {db_prefix}members
  456. WHERE id_member = {int:id_member}',
  457. array(
  458. 'id_member' => $memID,
  459. )
  460. );
  461. list ($user, $email, $lngfile) = $smcFunc['db_fetch_row']($request);
  462. $smcFunc['db_free_result']($request);
  463. if ($username !== null)
  464. {
  465. $old_user = $user;
  466. $user = trim($username);
  467. }
  468. // Generate a random password.
  469. $newPassword = substr(preg_replace('/\W/', '', md5(mt_rand())), 0, 10);
  470. $newPassword_sha1 = sha1(strtolower($user) . $newPassword);
  471. // Do some checks on the username if needed.
  472. if ($username !== null)
  473. {
  474. validateUsername($memID, $user);
  475. // Update the database...
  476. updateMemberData($memID, array('member_name' => $user, 'passwd' => $newPassword_sha1));
  477. }
  478. else
  479. updateMemberData($memID, array('passwd' => $newPassword_sha1));
  480. call_integration_hook('integrate_reset_pass', array($old_user, $user, $newPassword));
  481. $replacements = array(
  482. 'USERNAME' => $user,
  483. 'PASSWORD' => $newPassword,
  484. );
  485. $emaildata = loadEmailTemplate('change_password', $replacements, empty($lngfile) || empty($modSettings['userLanguage']) ? $language : $lngfile);
  486. // Send them the email informing them of the change - then we're done!
  487. sendmail($email, $emaildata['subject'], $emaildata['body'], null, null, false, 0);
  488. }
  489. /**
  490. * Checks a username obeys a load of rules
  491. * @param int $memID,
  492. * @param string $username
  493. * @return string Returns null if fine
  494. */
  495. function validateUsername($memID, $username)
  496. {
  497. global $sourcedir, $txt;
  498. // No name?! How can you register with no name?
  499. if ($username == '')
  500. fatal_lang_error('need_username', false);
  501. // Only these characters are permitted.
  502. if (in_array($username, array('_', '|')) || preg_match('~[<>&"\'=\\\\]~', preg_replace('~&#(?:\\d{1,7}|x[0-9a-fA-F]{1,6});~', '', $username)) != 0 || strpos($username, '[code') !== false || strpos($username, '[/code') !== false)
  503. fatal_lang_error('error_invalid_characters_username', false);
  504. if (stristr($username, $txt['guest_title']) !== false)
  505. fatal_lang_error('username_reserved', true, array($txt['guest_title']));
  506. require_once($sourcedir . '/Subs-Members.php');
  507. if (isReservedName($username, $memID, false))
  508. fatal_error('(' . htmlspecialchars($username) . ') ' . $txt['name_in_use'], false);
  509. return null;
  510. }
  511. /**
  512. * Checks whether a password meets the current forum rules
  513. * called when registering/choosing a password.
  514. * checks the password obeys the current forum settings for password strength.
  515. * if password checking is enabled, will check that none of the words in restrict_in appear in the password.
  516. * returns an error identifier if the password is invalid, or null.
  517. * @param string $password
  518. * @param string $username
  519. * @param array $restrict_in = array()
  520. * @return string an error identifier if the password is invalid
  521. */
  522. function validatePassword($password, $username, $restrict_in = array())
  523. {
  524. global $modSettings, $smcFunc;
  525. // Perform basic requirements first.
  526. if ($smcFunc['strlen']($password) < (empty($modSettings['password_strength']) ? 4 : 8))
  527. return 'short';
  528. // Is this enough?
  529. if (empty($modSettings['password_strength']))
  530. return null;
  531. // Otherwise, perform the medium strength test - checking if password appears in the restricted string.
  532. if (preg_match('~\b' . preg_quote($password, '~') . '\b~', implode(' ', $restrict_in)) != 0)
  533. return 'restricted_words';
  534. elseif ($smcFunc['strpos']($password, $username) !== false)
  535. return 'restricted_words';
  536. // @todo If pspell is available, use it on the word, and return restricted_words if it doesn't give "bad spelling"?
  537. // If just medium, we're done.
  538. if ($modSettings['password_strength'] == 1)
  539. return null;
  540. // Otherwise, hard test next, check for numbers and letters, uppercase too.
  541. $good = preg_match('~(\D\d|\d\D)~', $password) != 0;
  542. $good &= $smcFunc['strtolower']($password) != $password;
  543. return $good ? null : 'chars';
  544. }
  545. /**
  546. * Quickly find out what this user can and cannot do.
  547. * stores some useful information on the current users moderation powers in the session.
  548. */
  549. function rebuildModCache()
  550. {
  551. global $user_info, $smcFunc;
  552. // What groups can they moderate?
  553. $group_query = allowedTo('manage_membergroups') ? '1=1' : '0=1';
  554. if ($group_query == '0=1')
  555. {
  556. $request = $smcFunc['db_query']('', '
  557. SELECT id_group
  558. FROM {db_prefix}group_moderators
  559. WHERE id_member = {int:current_member}',
  560. array(
  561. 'current_member' => $user_info['id'],
  562. )
  563. );
  564. $groups = array();
  565. while ($row = $smcFunc['db_fetch_assoc']($request))
  566. $groups[] = $row['id_group'];
  567. $smcFunc['db_free_result']($request);
  568. if (empty($groups))
  569. $group_query = '0=1';
  570. else
  571. $group_query = 'id_group IN (' . implode(',', $groups) . ')';
  572. }
  573. // Then, same again, just the boards this time!
  574. $board_query = allowedTo('moderate_forum') ? '1=1' : '0=1';
  575. if ($board_query == '0=1')
  576. {
  577. $boards = boardsAllowedTo('moderate_board', true);
  578. if (empty($boards))
  579. $board_query = '0=1';
  580. else
  581. $board_query = 'id_board IN (' . implode(',', $boards) . ')';
  582. }
  583. // What boards are they the moderator of?
  584. $boards_mod = array();
  585. if (!$user_info['is_guest'])
  586. {
  587. $request = $smcFunc['db_query']('', '
  588. SELECT id_board
  589. FROM {db_prefix}moderators
  590. WHERE id_member = {int:current_member}',
  591. array(
  592. 'current_member' => $user_info['id'],
  593. )
  594. );
  595. while ($row = $smcFunc['db_fetch_assoc']($request))
  596. $boards_mod[] = $row['id_board'];
  597. $smcFunc['db_free_result']($request);
  598. }
  599. $mod_query = empty($boards_mod) ? '0=1' : 'b.id_board IN (' . implode(',', $boards_mod) . ')';
  600. $_SESSION['mc'] = array(
  601. 'time' => time(),
  602. // This looks a bit funny but protects against the login redirect.
  603. 'id' => $user_info['id'] && $user_info['name'] ? $user_info['id'] : 0,
  604. // If you change the format of 'gq' and/or 'bq' make sure to adjust 'can_mod' in Load.php.
  605. 'gq' => $group_query,
  606. 'bq' => $board_query,
  607. 'ap' => boardsAllowedTo('approve_posts'),
  608. 'mb' => $boards_mod,
  609. 'mq' => $mod_query,
  610. );
  611. $user_info['mod_cache'] = $_SESSION['mc'];
  612. // Might as well clean up some tokens while we are at it.
  613. cleanTokens();
  614. }
  615. ?>