Subs-Auth.php 26 KB

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