Subs-Auth.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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.1 Alpha 1
  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($type = 'admin')
  202. {
  203. global $context, $scripturl, $txt, $user_info, $user_settings;
  204. loadLanguage('Admin');
  205. loadTemplate('Login');
  206. // Validate what type of session check this is.
  207. $types = array();
  208. call_integration_hook('integrate_validateSession', array($types));
  209. $type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';
  210. // They used a wrong password, log it and unset that.
  211. if (isset($_POST[$type . '_hash_pass']) || isset($_POST[$type . '_pass']))
  212. {
  213. $txt['security_wrong'] = sprintf($txt['security_wrong'], isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $txt['unknown'], $_SERVER['HTTP_USER_AGENT'], $user_info['ip']);
  214. log_error($txt['security_wrong'], 'critical');
  215. if (isset($_POST[$type . '_hash_pass']))
  216. unset($_POST[$type . '_hash_pass']);
  217. if (isset($_POST[$type . '_pass']))
  218. unset($_POST[$type . '_pass']);
  219. $context['incorrect_password'] = true;
  220. }
  221. createToken('admin-login');
  222. // Figure out the get data and post data.
  223. $context['get_data'] = '?' . construct_query_string($_GET);
  224. $context['post_data'] = '';
  225. // Now go through $_POST. Make sure the session hash is sent.
  226. $_POST[$context['session_var']] = $context['session_id'];
  227. foreach ($_POST as $k => $v)
  228. $context['post_data'] .= adminLogin_outputPostVars($k, $v);
  229. // Now we'll use the admin_login sub template of the Login template.
  230. $context['sub_template'] = 'admin_login';
  231. // And title the page something like "Login".
  232. if (!isset($context['page_title']))
  233. $context['page_title'] = $txt['login'];
  234. // The type of action.
  235. $context['sessionCheckType'] = $type;
  236. obExit();
  237. // We MUST exit at this point, because otherwise we CANNOT KNOW that the user is privileged.
  238. trigger_error('Hacking attempt...', E_USER_ERROR);
  239. }
  240. function adminLogin_outputPostVars($k, $v)
  241. {
  242. global $smcFunc;
  243. if (!is_array($v))
  244. return '
  245. <input type="hidden" name="' . htmlspecialchars($k) . '" value="' . strtr($v, array('"' => '&quot;', '<' => '&lt;', '>' => '&gt;')) . '" />';
  246. else
  247. {
  248. $ret = '';
  249. foreach ($v as $k2 => $v2)
  250. $ret .= adminLogin_outputPostVars($k . '[' . $k2 . ']', $v2);
  251. return $ret;
  252. }
  253. }
  254. function construct_query_string($get)
  255. {
  256. global $scripturl;
  257. $query_string = '';
  258. // Awww, darn. The $scripturl contains GET stuff!
  259. $q = strpos($scripturl, '?');
  260. if ($q !== false)
  261. {
  262. parse_str(preg_replace('/&(\w+)(?=&|$)/', '&$1=', strtr(substr($scripturl, $q + 1), ';', '&')), $temp);
  263. foreach ($get as $k => $v)
  264. {
  265. // Only if it's not already in the $scripturl!
  266. if (!isset($temp[$k]))
  267. $query_string .= urlencode($k) . '=' . urlencode($v) . ';';
  268. // If it changed, put it out there, but with an ampersand.
  269. elseif ($temp[$k] != $get[$k])
  270. $query_string .= urlencode($k) . '=' . urlencode($v) . '&amp;';
  271. }
  272. }
  273. else
  274. {
  275. // Add up all the data from $_GET into get_data.
  276. foreach ($get as $k => $v)
  277. $query_string .= urlencode($k) . '=' . urlencode($v) . ';';
  278. }
  279. $query_string = substr($query_string, 0, -1);
  280. return $query_string;
  281. }
  282. // Find members by email address, username, or real name.
  283. function findMembers($names, $use_wildcards = false, $buddies_only = false, $max = 500)
  284. {
  285. global $scripturl, $user_info, $modSettings, $smcFunc;
  286. // If it's not already an array, make it one.
  287. if (!is_array($names))
  288. $names = explode(',', $names);
  289. $maybe_email = false;
  290. foreach ($names as $i => $name)
  291. {
  292. // Trim, and fix wildcards for each name.
  293. $names[$i] = trim($smcFunc['strtolower']($name));
  294. $maybe_email |= strpos($name, '@') !== false;
  295. // Make it so standard wildcards will work. (* and ?)
  296. if ($use_wildcards)
  297. $names[$i] = strtr($names[$i], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '\'' => '&#039;'));
  298. else
  299. $names[$i] = strtr($names[$i], array('\'' => '&#039;'));
  300. }
  301. // What are we using to compare?
  302. $comparison = $use_wildcards ? 'LIKE' : '=';
  303. // Nothing found yet.
  304. $results = array();
  305. // This ensures you can't search someones email address if you can't see it.
  306. $email_condition = allowedTo('moderate_forum') ? '' : 'hide_email = 0 AND ';
  307. if ($use_wildcards || $maybe_email)
  308. $email_condition = '
  309. OR (' . $email_condition . 'email_address ' . $comparison . ' \'' . implode( '\') OR (' . $email_condition . ' email_address ' . $comparison . ' \'', $names) . '\')';
  310. else
  311. $email_condition = '';
  312. // Get the case of the columns right - but only if we need to as things like MySQL will go slow needlessly otherwise.
  313. $member_name = $smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name';
  314. $real_name = $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name';
  315. // Search by username, display name, and email address.
  316. $request = $smcFunc['db_query']('', '
  317. SELECT id_member, member_name, real_name, email_address, hide_email
  318. FROM {db_prefix}members
  319. WHERE ({raw:member_name_search}
  320. OR {raw:real_name_search} {raw:email_condition})
  321. ' . ($buddies_only ? 'AND id_member IN ({array_int:buddy_list})' : '') . '
  322. AND is_activated IN (1, 11)
  323. LIMIT {int:limit}',
  324. array(
  325. 'buddy_list' => $user_info['buddies'],
  326. 'member_name_search' => $member_name . ' ' . $comparison . ' \'' . implode( '\' OR ' . $member_name . ' ' . $comparison . ' \'', $names) . '\'',
  327. 'real_name_search' => $real_name . ' ' . $comparison . ' \'' . implode( '\' OR ' . $real_name . ' ' . $comparison . ' \'', $names) . '\'',
  328. 'email_condition' => $email_condition,
  329. 'limit' => $max,
  330. )
  331. );
  332. while ($row = $smcFunc['db_fetch_assoc']($request))
  333. {
  334. $results[$row['id_member']] = array(
  335. 'id' => $row['id_member'],
  336. 'name' => $row['real_name'],
  337. 'username' => $row['member_name'],
  338. 'email' => in_array(showEmailAddress(!empty($row['hide_email']), $row['id_member']), array('yes', 'yes_permission_override')) ? $row['email_address'] : '',
  339. 'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
  340. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>'
  341. );
  342. }
  343. $smcFunc['db_free_result']($request);
  344. // Return all the results.
  345. return $results;
  346. }
  347. function JSMembers()
  348. {
  349. global $context, $scripturl, $user_info, $smcFunc;
  350. checkSession('get');
  351. if (WIRELESS)
  352. $context['sub_template'] = WIRELESS_PROTOCOL . '_pm';
  353. else
  354. {
  355. // Why is this in the Help template, you ask? Well, erm... it helps you. Does that work?
  356. loadTemplate('Help');
  357. $context['template_layers'] = array();
  358. $context['sub_template'] = 'find_members';
  359. }
  360. if (isset($_REQUEST['search']))
  361. $context['last_search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
  362. else
  363. $_REQUEST['start'] = 0;
  364. // Allow the user to pass the input to be added to to the box.
  365. $context['input_box_name'] = isset($_REQUEST['input']) && preg_match('~^[\w-]+$~', $_REQUEST['input']) === 1 ? $_REQUEST['input'] : 'to';
  366. // Take the delimiter over GET in case it's \n or something.
  367. $context['delimiter'] = isset($_REQUEST['delim']) ? ($_REQUEST['delim'] == 'LB' ? "\n" : $_REQUEST['delim']) : ', ';
  368. $context['quote_results'] = !empty($_REQUEST['quote']);
  369. // List all the results.
  370. $context['results'] = array();
  371. // Some buddy related settings ;)
  372. $context['show_buddies'] = !empty($user_info['buddies']);
  373. $context['buddy_search'] = isset($_REQUEST['buddies']);
  374. // If the user has done a search, well - search.
  375. if (isset($_REQUEST['search']))
  376. {
  377. $_REQUEST['search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
  378. $context['results'] = findMembers(array($_REQUEST['search']), true, $context['buddy_search']);
  379. $total_results = count($context['results']);
  380. $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);
  381. // Determine the navigation context (especially useful for the wireless template).
  382. $base_url = $scripturl . '?action=findmember;search=' . urlencode($context['last_search']) . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']) . ';' . $context['session_var'] . '=' . $context['session_id'];
  383. $context['links'] = array(
  384. 'first' => $_REQUEST['start'] >= 7 ? $base_url . ';start=0' : '',
  385. 'prev' => $_REQUEST['start'] >= 7 ? $base_url . ';start=' . ($_REQUEST['start'] - 7) : '',
  386. 'next' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . ($_REQUEST['start'] + 7) : '',
  387. 'last' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . (floor(($total_results - 1) / 7) * 7) : '',
  388. 'up' => $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']),
  389. );
  390. $context['page_info'] = array(
  391. 'current_page' => $_REQUEST['start'] / 7 + 1,
  392. 'num_pages' => floor(($total_results - 1) / 7) + 1
  393. );
  394. $context['results'] = array_slice($context['results'], $_REQUEST['start'], 7);
  395. }
  396. else
  397. $context['links']['up'] = $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']);
  398. }
  399. function RequestMembers()
  400. {
  401. global $user_info, $txt, $smcFunc;
  402. checkSession('get');
  403. $_REQUEST['search'] = $smcFunc['htmlspecialchars']($_REQUEST['search']) . '*';
  404. $_REQUEST['search'] = trim($smcFunc['strtolower']($_REQUEST['search']));
  405. $_REQUEST['search'] = strtr($_REQUEST['search'], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '&#038;' => '&amp;'));
  406. if (function_exists('iconv'))
  407. header('Content-Type: text/plain; charset=UTF-8');
  408. $request = $smcFunc['db_query']('', '
  409. SELECT real_name
  410. FROM {db_prefix}members
  411. WHERE real_name LIKE {string:search}' . (isset($_REQUEST['buddies']) ? '
  412. AND id_member IN ({array_int:buddy_list})' : '') . '
  413. AND is_activated IN (1, 11)
  414. LIMIT ' . ($smcFunc['strlen']($_REQUEST['search']) <= 2 ? '100' : '800'),
  415. array(
  416. 'buddy_list' => $user_info['buddies'],
  417. 'search' => $_REQUEST['search'],
  418. )
  419. );
  420. while ($row = $smcFunc['db_fetch_assoc']($request))
  421. {
  422. if (function_exists('iconv'))
  423. {
  424. $utf8 = iconv($txt['lang_character_set'], 'UTF-8', $row['real_name']);
  425. if ($utf8)
  426. $row['real_name'] = $utf8;
  427. }
  428. $row['real_name'] = strtr($row['real_name'], array('&amp;' => '&#038;', '&lt;' => '&#060;', '&gt;' => '&#062;', '&quot;' => '&#034;'));
  429. if (preg_match('~&#\d+;~', $row['real_name']) != 0)
  430. {
  431. $fixchar = create_function('$n', '
  432. if ($n < 128)
  433. return chr($n);
  434. elseif ($n < 2048)
  435. return chr(192 | $n >> 6) . chr(128 | $n & 63);
  436. elseif ($n < 65536)
  437. return chr(224 | $n >> 12) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);
  438. else
  439. return chr(240 | $n >> 18) . chr(128 | $n >> 12 & 63) . chr(128 | $n >> 6 & 63) . chr(128 | $n & 63);');
  440. $row['real_name'] = preg_replace('~&#(\d+);~e', '$fixchar(\'$1\')', $row['real_name']);
  441. }
  442. echo $row['real_name'], "\n";
  443. }
  444. $smcFunc['db_free_result']($request);
  445. obExit(false);
  446. }
  447. // This function generates a random password for a user and emails it to them.
  448. function resetPassword($memID, $username = null)
  449. {
  450. global $scripturl, $context, $txt, $sourcedir, $modSettings, $smcFunc, $language;
  451. // Language... and a required file.
  452. loadLanguage('Login');
  453. require_once($sourcedir . '/Subs-Post.php');
  454. // Get some important details.
  455. $request = $smcFunc['db_query']('', '
  456. SELECT member_name, email_address, lngfile
  457. FROM {db_prefix}members
  458. WHERE id_member = {int:id_member}',
  459. array(
  460. 'id_member' => $memID,
  461. )
  462. );
  463. list ($user, $email, $lngfile) = $smcFunc['db_fetch_row']($request);
  464. $smcFunc['db_free_result']($request);
  465. if ($username !== null)
  466. {
  467. $old_user = $user;
  468. $user = trim($username);
  469. }
  470. // Generate a random password.
  471. $newPassword = substr(preg_replace('/\W/', '', md5(mt_rand())), 0, 10);
  472. $newPassword_sha1 = sha1(strtolower($user) . $newPassword);
  473. // Do some checks on the username if needed.
  474. if ($username !== null)
  475. {
  476. validateUsername($memID, $user);
  477. // Update the database...
  478. updateMemberData($memID, array('member_name' => $user, 'passwd' => $newPassword_sha1));
  479. }
  480. else
  481. updateMemberData($memID, array('passwd' => $newPassword_sha1));
  482. call_integration_hook('integrate_reset_pass', array($old_user, $user, $newPassword));
  483. $replacements = array(
  484. 'USERNAME' => $user,
  485. 'PASSWORD' => $newPassword,
  486. );
  487. $emaildata = loadEmailTemplate('change_password', $replacements, empty($lngfile) || empty($modSettings['userLanguage']) ? $language : $lngfile);
  488. // Send them the email informing them of the change - then we're done!
  489. sendmail($email, $emaildata['subject'], $emaildata['body'], null, null, false, 0);
  490. }
  491. // Is this a valid username?
  492. function validateUsername($memID, $username)
  493. {
  494. global $sourcedir, $txt;
  495. // No name?! How can you register with no name?
  496. if ($username == '')
  497. fatal_lang_error('need_username', false);
  498. // Only these characters are permitted.
  499. 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)
  500. fatal_lang_error('error_invalid_characters_username', false);
  501. if (stristr($username, $txt['guest_title']) !== false)
  502. fatal_lang_error('username_reserved', true, array($txt['guest_title']));
  503. require_once($sourcedir . '/Subs-Members.php');
  504. if (isReservedName($username, $memID, false))
  505. fatal_error('(' . htmlspecialchars($username) . ') ' . $txt['name_in_use'], false);
  506. return null;
  507. }
  508. // This function simply checks whether a password meets the current forum rules.
  509. function validatePassword($password, $username, $restrict_in = array())
  510. {
  511. global $modSettings, $smcFunc;
  512. // Perform basic requirements first.
  513. if ($smcFunc['strlen']($password) < (empty($modSettings['password_strength']) ? 4 : 8))
  514. return 'short';
  515. // Is this enough?
  516. if (empty($modSettings['password_strength']))
  517. return null;
  518. // Otherwise, perform the medium strength test - checking if password appears in the restricted string.
  519. if (preg_match('~\b' . preg_quote($password, '~') . '\b~', implode(' ', $restrict_in)) != 0)
  520. return 'restricted_words';
  521. elseif ($smcFunc['strpos']($password, $username) !== false)
  522. return 'restricted_words';
  523. // @todo If pspell is available, use it on the word, and return restricted_words if it doesn't give "bad spelling"?
  524. // If just medium, we're done.
  525. if ($modSettings['password_strength'] == 1)
  526. return null;
  527. // Otherwise, hard test next, check for numbers and letters, uppercase too.
  528. $good = preg_match('~(\D\d|\d\D)~', $password) != 0;
  529. $good &= $smcFunc['strtolower']($password) != $password;
  530. return $good ? null : 'chars';
  531. }
  532. // Quickly find out what this user can and cannot do.
  533. function rebuildModCache()
  534. {
  535. global $user_info, $smcFunc;
  536. // What groups can they moderate?
  537. $group_query = allowedTo('manage_membergroups') ? '1=1' : '0=1';
  538. if ($group_query == '0=1')
  539. {
  540. $request = $smcFunc['db_query']('', '
  541. SELECT id_group
  542. FROM {db_prefix}group_moderators
  543. WHERE id_member = {int:current_member}',
  544. array(
  545. 'current_member' => $user_info['id'],
  546. )
  547. );
  548. $groups = array();
  549. while ($row = $smcFunc['db_fetch_assoc']($request))
  550. $groups[] = $row['id_group'];
  551. $smcFunc['db_free_result']($request);
  552. if (empty($groups))
  553. $group_query = '0=1';
  554. else
  555. $group_query = 'id_group IN (' . implode(',', $groups) . ')';
  556. }
  557. // Then, same again, just the boards this time!
  558. $board_query = allowedTo('moderate_forum') ? '1=1' : '0=1';
  559. if ($board_query == '0=1')
  560. {
  561. $boards = boardsAllowedTo('moderate_board', true);
  562. if (empty($boards))
  563. $board_query = '0=1';
  564. else
  565. $board_query = 'id_board IN (' . implode(',', $boards) . ')';
  566. }
  567. // What boards are they the moderator of?
  568. $boards_mod = array();
  569. if (!$user_info['is_guest'])
  570. {
  571. $request = $smcFunc['db_query']('', '
  572. SELECT id_board
  573. FROM {db_prefix}moderators
  574. WHERE id_member = {int:current_member}',
  575. array(
  576. 'current_member' => $user_info['id'],
  577. )
  578. );
  579. while ($row = $smcFunc['db_fetch_assoc']($request))
  580. $boards_mod[] = $row['id_board'];
  581. $smcFunc['db_free_result']($request);
  582. }
  583. $mod_query = empty($boards_mod) ? '0=1' : 'b.id_board IN (' . implode(',', $boards_mod) . ')';
  584. $_SESSION['mc'] = array(
  585. 'time' => time(),
  586. // This looks a bit funny but protects against the login redirect.
  587. 'id' => $user_info['id'] && $user_info['name'] ? $user_info['id'] : 0,
  588. // If you change the format of 'gq' and/or 'bq' make sure to adjust 'can_mod' in Load.php.
  589. 'gq' => $group_query,
  590. 'bq' => $board_query,
  591. 'ap' => boardsAllowedTo('approve_posts'),
  592. 'mb' => $boards_mod,
  593. 'mq' => $mod_query,
  594. );
  595. $user_info['mod_cache'] = $_SESSION['mc'];
  596. // Might as well clean up some tokens while we are at it.
  597. cleanTokens();
  598. }
  599. ?>