Subs-Auth.php 25 KB

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