Subs-Auth.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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 2014 Simple Machines and individual contributors
  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('No direct access...');
  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. *
  23. * @param int $cookie_length
  24. * @param int $id The id of the member
  25. * @param string $password = ''
  26. */
  27. function setLoginCookie($cookie_length, $id, $password = '')
  28. {
  29. global $cookiename, $boardurl, $modSettings, $sourcedir;
  30. $id = (int) $id;
  31. // If changing state force them to re-address some permission caching.
  32. $_SESSION['mc']['time'] = 0;
  33. // The cookie may already exist, and have been set with different options.
  34. $cookie_state = (empty($modSettings['localCookies']) ? 0 : 1) | (empty($modSettings['globalCookies']) ? 0 : 2);
  35. if (isset($_COOKIE[$cookiename]) && preg_match('~^a:[34]:\{i:0;i:\d{1,7};i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~', $_COOKIE[$cookiename]) === 1)
  36. {
  37. $array = @unserialize($_COOKIE[$cookiename]);
  38. // Out with the old, in with the new!
  39. if (isset($array[3]) && $array[3] != $cookie_state)
  40. {
  41. $cookie_url = url_parts($array[3] & 1 > 0, $array[3] & 2 > 0);
  42. smf_setcookie($cookiename, serialize(array(0, '', 0)), time() - 3600, $cookie_url[1], $cookie_url[0]);
  43. }
  44. }
  45. // Get the data and path to set it on.
  46. $data = serialize(empty($id) ? array(0, '', 0) : array($id, $password, time() + $cookie_length, $cookie_state));
  47. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  48. // Set the cookie, $_COOKIE, and session variable.
  49. smf_setcookie($cookiename, $data, time() + $cookie_length, $cookie_url[1], $cookie_url[0]);
  50. // If subdomain-independent cookies are on, unset the subdomain-dependent cookie too.
  51. if (empty($id) && !empty($modSettings['globalCookies']))
  52. smf_setcookie($cookiename, $data, time() + $cookie_length, $cookie_url[1], '');
  53. // Any alias URLs? This is mainly for use with frames, etc.
  54. if (!empty($modSettings['forum_alias_urls']))
  55. {
  56. $aliases = explode(',', $modSettings['forum_alias_urls']);
  57. $temp = $boardurl;
  58. foreach ($aliases as $alias)
  59. {
  60. // Fake the $boardurl so we can set a different cookie.
  61. $alias = strtr(trim($alias), array('http://' => '', 'https://' => ''));
  62. $boardurl = 'http://' . $alias;
  63. $cookie_url = url_parts(!empty($modSettings['localCookies']), !empty($modSettings['globalCookies']));
  64. if ($cookie_url[0] == '')
  65. $cookie_url[0] = strtok($alias, '/');
  66. smf_setcookie($cookiename, $data, time() + $cookie_length, $cookie_url[1], $cookie_url[0]);
  67. }
  68. $boardurl = $temp;
  69. }
  70. $_COOKIE[$cookiename] = $data;
  71. // Make sure the user logs in with a new session ID.
  72. if (!isset($_SESSION['login_' . $cookiename]) || $_SESSION['login_' . $cookiename] !== $data)
  73. {
  74. // We need to meddle with the session.
  75. require_once($sourcedir . '/Session.php');
  76. // Backup and remove the old session.
  77. $oldSessionData = $_SESSION;
  78. $_SESSION = array();
  79. session_destroy();
  80. // Recreate and restore the new session.
  81. loadSession();
  82. // @todo should we use session_regenerate_id(true); now that we are 5.1+
  83. session_regenerate_id();
  84. $_SESSION = $oldSessionData;
  85. $_SESSION['login_' . $cookiename] = $data;
  86. }
  87. }
  88. /**
  89. * Get the domain and path for the cookie
  90. * - normally, local and global should be the localCookies and globalCookies settings, respectively.
  91. * - uses boardurl to determine these two things.
  92. *
  93. * @param bool $local
  94. * @param bool $global
  95. * @return array an array to set the cookie on with domain and path in it, in that order
  96. */
  97. function url_parts($local, $global)
  98. {
  99. global $boardurl, $modSettings;
  100. // Parse the URL with PHP to make life easier.
  101. $parsed_url = parse_url($boardurl);
  102. // Is local cookies off?
  103. if (empty($parsed_url['path']) || !$local)
  104. $parsed_url['path'] = '';
  105. if (!empty($modSettings['globalCookiesDomain']) && strpos($boardurl, $modSettings['globalCookiesDomain']) !== false)
  106. $parsed_url['host'] = $modSettings['globalCookiesDomain'];
  107. // Globalize cookies across domains (filter out IP-addresses)?
  108. elseif ($global && preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $parsed_url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $parsed_url['host'], $parts) == 1)
  109. $parsed_url['host'] = '.' . $parts[1];
  110. // We shouldn't use a host at all if both options are off.
  111. elseif (!$local && !$global)
  112. $parsed_url['host'] = '';
  113. // The host also shouldn't be set if there aren't any dots in it.
  114. elseif (!isset($parsed_url['host']) || strpos($parsed_url['host'], '.') === false)
  115. $parsed_url['host'] = '';
  116. return array($parsed_url['host'], $parsed_url['path'] . '/');
  117. }
  118. /**
  119. * Throws guests out to the login screen when guest access is off.
  120. * - sets $_SESSION['login_url'] to $_SERVER['REQUEST_URL'].
  121. * - uses the 'kick_guest' sub template found in Login.template.php.
  122. */
  123. function KickGuest()
  124. {
  125. global $txt, $context;
  126. loadLanguage('Login');
  127. loadTemplate('Login');
  128. createToken('login');
  129. // Need some js goodies.
  130. loadJavascriptFile('sha1.js', array('default_theme' => true), 'smf_scripts');
  131. // Never redirect to an attachment
  132. if (strpos($_SERVER['REQUEST_URL'], 'dlattach') === false)
  133. $_SESSION['login_url'] = $_SERVER['REQUEST_URL'];
  134. $context['sub_template'] = 'kick_guest';
  135. $context['page_title'] = $txt['login'];
  136. }
  137. /**
  138. * Display a message about the forum being in maintenance mode.
  139. * - display a login screen with sub template 'maintenance'.
  140. * - sends a 503 header, so search engines don't bother indexing while we're in maintenance mode.
  141. */
  142. function InMaintenance()
  143. {
  144. global $txt, $mtitle, $mmessage, $context;
  145. loadLanguage('Login');
  146. loadTemplate('Login');
  147. createToken('login');
  148. loadJavascriptFile('sha1.js', array('default_theme' => true), 'smf_scripts');
  149. // Send a 503 header, so search engines don't bother indexing while we're in maintenance mode.
  150. header('HTTP/1.1 503 Service Temporarily Unavailable');
  151. // Basic template stuff..
  152. $context['sub_template'] = 'maintenance';
  153. $context['title'] = &$mtitle;
  154. $context['description'] = &$mmessage;
  155. $context['page_title'] = $txt['maintain_mode'];
  156. }
  157. /**
  158. * Question the verity of the admin by asking for his or her password.
  159. * - loads Login.template.php and uses the admin_login sub template.
  160. * - sends data to template so the admin is sent on to the page they
  161. * wanted if their password is correct, otherwise they can try again.
  162. *
  163. * @param string $type = 'admin'
  164. */
  165. function adminLogin($type = 'admin')
  166. {
  167. global $context, $scripturl, $txt, $user_info, $user_settings;
  168. loadLanguage('Admin');
  169. loadTemplate('Login');
  170. loadJavascriptFile('sha1.js', array('default_theme' => true), 'smf_scripts');
  171. // Validate what type of session check this is.
  172. $types = array();
  173. call_integration_hook('integrate_validateSession', array(&$types));
  174. $type = in_array($type, $types) || $type == 'moderate' ? $type : 'admin';
  175. // They used a wrong password, log it and unset that.
  176. if (isset($_POST[$type . '_hash_pass']) || isset($_POST[$type . '_pass']))
  177. {
  178. $txt['security_wrong'] = sprintf($txt['security_wrong'], isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $txt['unknown'], $_SERVER['HTTP_USER_AGENT'], $user_info['ip']);
  179. log_error($txt['security_wrong'], 'critical');
  180. if (isset($_POST[$type . '_hash_pass']))
  181. unset($_POST[$type . '_hash_pass']);
  182. if (isset($_POST[$type . '_pass']))
  183. unset($_POST[$type . '_pass']);
  184. $context['incorrect_password'] = true;
  185. }
  186. createToken('admin-login');
  187. // Figure out the get data and post data.
  188. $context['get_data'] = '?' . construct_query_string($_GET);
  189. $context['post_data'] = '';
  190. // Now go through $_POST. Make sure the session hash is sent.
  191. $_POST[$context['session_var']] = $context['session_id'];
  192. foreach ($_POST as $k => $v)
  193. $context['post_data'] .= adminLogin_outputPostVars($k, $v);
  194. // Now we'll use the admin_login sub template of the Login template.
  195. $context['sub_template'] = 'admin_login';
  196. // And title the page something like "Login".
  197. if (!isset($context['page_title']))
  198. $context['page_title'] = $txt['login'];
  199. // The type of action.
  200. $context['sessionCheckType'] = $type;
  201. obExit();
  202. // We MUST exit at this point, because otherwise we CANNOT KNOW that the user is privileged.
  203. trigger_error('Hacking attempt...', E_USER_ERROR);
  204. }
  205. /**
  206. * Used by the adminLogin() function.
  207. * if 'value' is an array, the function is called recursively.
  208. *
  209. * @param string $k key
  210. * @param string $v value
  211. * @return string 'hidden' HTML form fields, containing key-value-pairs
  212. */
  213. function adminLogin_outputPostVars($k, $v)
  214. {
  215. global $smcFunc;
  216. if (!is_array($v))
  217. return '
  218. <input type="hidden" name="' . $smcFunc['htmlspecialchars']($k) . '" value="' . strtr($v, array('"' => '&quot;', '<' => '&lt;', '>' => '&gt;')) . '">';
  219. else
  220. {
  221. $ret = '';
  222. foreach ($v as $k2 => $v2)
  223. $ret .= adminLogin_outputPostVars($k . '[' . $k2 . ']', $v2);
  224. return $ret;
  225. }
  226. }
  227. /**
  228. * Properly urlencodes a string to be used in a query
  229. *
  230. * @global type $scripturl
  231. * @param type $get
  232. * @return our query string
  233. */
  234. function construct_query_string($get)
  235. {
  236. global $scripturl;
  237. $query_string = '';
  238. // Awww, darn. The $scripturl contains GET stuff!
  239. $q = strpos($scripturl, '?');
  240. if ($q !== false)
  241. {
  242. parse_str(preg_replace('/&(\w+)(?=&|$)/', '&$1=', strtr(substr($scripturl, $q + 1), ';', '&')), $temp);
  243. foreach ($get as $k => $v)
  244. {
  245. // Only if it's not already in the $scripturl!
  246. if (!isset($temp[$k]))
  247. $query_string .= urlencode($k) . '=' . urlencode($v) . ';';
  248. // If it changed, put it out there, but with an ampersand.
  249. elseif ($temp[$k] != $get[$k])
  250. $query_string .= urlencode($k) . '=' . urlencode($v) . '&amp;';
  251. }
  252. }
  253. else
  254. {
  255. // Add up all the data from $_GET into get_data.
  256. foreach ($get as $k => $v)
  257. $query_string .= urlencode($k) . '=' . urlencode($v) . ';';
  258. }
  259. $query_string = substr($query_string, 0, -1);
  260. return $query_string;
  261. }
  262. /**
  263. * Finds members by email address, username, or real name.
  264. * - searches for members whose username, display name, or e-mail address match the given pattern of array names.
  265. * - searches only buddies if buddies_only is set.
  266. *
  267. * @param array $names
  268. * @param bool $use_wildcards = false, accepts wildcards ? and * in the patern if true
  269. * @param bool $buddies_only = false,
  270. * @param int $max = 500 retrieves a maximum of max members, if passed
  271. * @return array containing information about the matching members
  272. */
  273. function findMembers($names, $use_wildcards = false, $buddies_only = false, $max = 500)
  274. {
  275. global $scripturl, $user_info, $smcFunc;
  276. // If it's not already an array, make it one.
  277. if (!is_array($names))
  278. $names = explode(',', $names);
  279. $maybe_email = false;
  280. foreach ($names as $i => $name)
  281. {
  282. // Trim, and fix wildcards for each name.
  283. $names[$i] = trim($smcFunc['strtolower']($name));
  284. $maybe_email |= strpos($name, '@') !== false;
  285. // Make it so standard wildcards will work. (* and ?)
  286. if ($use_wildcards)
  287. $names[$i] = strtr($names[$i], array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_', '\'' => '&#039;'));
  288. else
  289. $names[$i] = strtr($names[$i], array('\'' => '&#039;'));
  290. }
  291. // What are we using to compare?
  292. $comparison = $use_wildcards ? 'LIKE' : '=';
  293. // Nothing found yet.
  294. $results = array();
  295. // This ensures you can't search someones email address if you can't see it.
  296. $email_condition = allowedTo('moderate_forum') ? '' : 'hide_email = 0 AND ';
  297. if ($use_wildcards || $maybe_email)
  298. $email_condition = '
  299. OR (' . $email_condition . 'email_address ' . $comparison . ' \'' . implode( '\') OR (' . $email_condition . ' email_address ' . $comparison . ' \'', $names) . '\')';
  300. else
  301. $email_condition = '';
  302. // Get the case of the columns right - but only if we need to as things like MySQL will go slow needlessly otherwise.
  303. $member_name = $smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name';
  304. $real_name = $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name';
  305. // Search by username, display name, and email address.
  306. $request = $smcFunc['db_query']('', '
  307. SELECT id_member, member_name, real_name, email_address, hide_email
  308. FROM {db_prefix}members
  309. WHERE ({raw:member_name_search}
  310. OR {raw:real_name_search} {raw:email_condition})
  311. ' . ($buddies_only ? 'AND id_member IN ({array_int:buddy_list})' : '') . '
  312. AND is_activated IN (1, 11)
  313. LIMIT {int:limit}',
  314. array(
  315. 'buddy_list' => $user_info['buddies'],
  316. 'member_name_search' => $member_name . ' ' . $comparison . ' \'' . implode( '\' OR ' . $member_name . ' ' . $comparison . ' \'', $names) . '\'',
  317. 'real_name_search' => $real_name . ' ' . $comparison . ' \'' . implode( '\' OR ' . $real_name . ' ' . $comparison . ' \'', $names) . '\'',
  318. 'email_condition' => $email_condition,
  319. 'limit' => $max,
  320. )
  321. );
  322. while ($row = $smcFunc['db_fetch_assoc']($request))
  323. {
  324. $results[$row['id_member']] = array(
  325. 'id' => $row['id_member'],
  326. 'name' => $row['real_name'],
  327. 'username' => $row['member_name'],
  328. 'email' => in_array(showEmailAddress(!empty($row['hide_email']), $row['id_member']), array('yes', 'yes_permission_override')) ? $row['email_address'] : '',
  329. 'href' => $scripturl . '?action=profile;u=' . $row['id_member'],
  330. 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>'
  331. );
  332. }
  333. $smcFunc['db_free_result']($request);
  334. // Return all the results.
  335. return $results;
  336. }
  337. /**
  338. * Called by index.php?action=findmember.
  339. * - is used as a popup for searching members.
  340. * - uses sub template find_members of the Help template.
  341. * - also used to add members for PM's sent using wap2/imode protocol.
  342. */
  343. function JSMembers()
  344. {
  345. global $context, $scripturl, $user_info, $smcFunc;
  346. checkSession('get');
  347. if (WIRELESS)
  348. $context['sub_template'] = WIRELESS_PROTOCOL . '_pm';
  349. else
  350. {
  351. // Why is this in the Help template, you ask? Well, erm... it helps you. Does that work?
  352. loadTemplate('Help');
  353. $context['template_layers'] = array();
  354. $context['sub_template'] = 'find_members';
  355. }
  356. if (isset($_REQUEST['search']))
  357. $context['last_search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
  358. else
  359. $_REQUEST['start'] = 0;
  360. // Allow the user to pass the input to be added to to the box.
  361. $context['input_box_name'] = isset($_REQUEST['input']) && preg_match('~^[\w-]+$~', $_REQUEST['input']) === 1 ? $_REQUEST['input'] : 'to';
  362. // Take the delimiter over GET in case it's \n or something.
  363. $context['delimiter'] = isset($_REQUEST['delim']) ? ($_REQUEST['delim'] == 'LB' ? "\n" : $_REQUEST['delim']) : ', ';
  364. $context['quote_results'] = !empty($_REQUEST['quote']);
  365. // List all the results.
  366. $context['results'] = array();
  367. // Some buddy related settings ;)
  368. $context['show_buddies'] = !empty($user_info['buddies']);
  369. $context['buddy_search'] = isset($_REQUEST['buddies']);
  370. // If the user has done a search, well - search.
  371. if (isset($_REQUEST['search']))
  372. {
  373. $_REQUEST['search'] = $smcFunc['htmlspecialchars']($_REQUEST['search'], ENT_QUOTES);
  374. $context['results'] = findMembers(array($_REQUEST['search']), true, $context['buddy_search']);
  375. $total_results = count($context['results']);
  376. $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);
  377. // Determine the navigation context (especially useful for the wireless template).
  378. $base_url = $scripturl . '?action=findmember;search=' . urlencode($context['last_search']) . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']) . ';' . $context['session_var'] . '=' . $context['session_id'];
  379. $context['links'] = array(
  380. 'first' => $_REQUEST['start'] >= 7 ? $base_url . ';start=0' : '',
  381. 'prev' => $_REQUEST['start'] >= 7 ? $base_url . ';start=' . ($_REQUEST['start'] - 7) : '',
  382. 'next' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . ($_REQUEST['start'] + 7) : '',
  383. 'last' => $_REQUEST['start'] + 7 < $total_results ? $base_url . ';start=' . (floor(($total_results - 1) / 7) * 7) : '',
  384. 'up' => $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']),
  385. );
  386. $context['page_info'] = array(
  387. 'current_page' => $_REQUEST['start'] / 7 + 1,
  388. 'num_pages' => floor(($total_results - 1) / 7) + 1
  389. );
  390. $context['results'] = array_slice($context['results'], $_REQUEST['start'], 7);
  391. }
  392. else
  393. $context['links']['up'] = $scripturl . '?action=pm;sa=send' . (empty($_REQUEST['u']) ? '' : ';u=' . $_REQUEST['u']);
  394. }
  395. /**
  396. * Outputs each member name on its own line.
  397. * - used by javascript to find members matching the request.
  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 {raw: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. 'real_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name',
  417. 'buddy_list' => $user_info['buddies'],
  418. 'search' => $_REQUEST['search'],
  419. )
  420. );
  421. while ($row = $smcFunc['db_fetch_assoc']($request))
  422. {
  423. if (function_exists('iconv'))
  424. {
  425. $utf8 = iconv($txt['lang_character_set'], 'UTF-8', $row['real_name']);
  426. if ($utf8)
  427. $row['real_name'] = $utf8;
  428. }
  429. $row['real_name'] = strtr($row['real_name'], array('&amp;' => '&#038;', '&lt;' => '&#060;', '&gt;' => '&#062;', '&quot;' => '&#034;'));
  430. if (preg_match('~&#\d+;~', $row['real_name']) != 0)
  431. $row['real_name'] = preg_replace_callback('~&#(\d+);~', 'fixchar__callback', $row['real_name']);
  432. echo $row['real_name'], "\n";
  433. }
  434. $smcFunc['db_free_result']($request);
  435. obExit(false);
  436. }
  437. /**
  438. * Generates a random password for a user and emails it to them.
  439. * - called by Profile.php when changing someone's username.
  440. * - checks the validity of the new username.
  441. * - generates and sets a new password for the given user.
  442. * - mails the new password to the email address of the user.
  443. * - if username is not set, only a new password is generated and sent.
  444. *
  445. * @param int $memID
  446. * @param string $username = null
  447. */
  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, 'chgpass' . $memID, false, 0);
  490. }
  491. /**
  492. * Checks a username obeys a load of rules
  493. *
  494. * @param int $memID
  495. * @param string $username
  496. * @param boolean $return_error
  497. * @param boolean $check_reserved_name
  498. * @return string Returns null if fine
  499. */
  500. function validateUsername($memID, $username, $return_error = false, $check_reserved_name = true)
  501. {
  502. global $sourcedir, $txt, $smcFunc, $user_info;
  503. $errors = array();
  504. // Don't use too long a name.
  505. if ($smcFunc['strlen']($username) > 25)
  506. $errors[] = array('lang', 'error_long_name');
  507. // No name?! How can you register with no name?
  508. if ($username == '')
  509. $errors[] = array('lang', 'need_username');
  510. // Only these characters are permitted.
  511. 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)
  512. $errors[] = array('lang', 'error_invalid_characters_username');
  513. if (stristr($username, $txt['guest_title']) !== false)
  514. $errors[] = array('lang', 'username_reserved', 'general', array($txt['guest_title']));
  515. if ($check_reserved_name)
  516. {
  517. require_once($sourcedir . '/Subs-Members.php');
  518. if (isReservedName($username, $memID, false))
  519. $errors[] = array('done', '(' . $smcFunc['htmlspecialchars']($username) . ') ' . $txt['name_in_use']);
  520. }
  521. if ($return_error)
  522. return $errors;
  523. elseif (empty($errors))
  524. return null;
  525. loadLanguage('Errors');
  526. $error = $errors[0];
  527. $message = $error[0] == 'lang' ? (empty($error[3]) ? $txt[$error[1]] : vsprintf($txt[$error[1]], $error[3])) : $error[1];
  528. fatal_error($message, empty($error[2]) || $user_info['is_admin'] ? false : $error[2]);
  529. }
  530. /**
  531. * Checks whether a password meets the current forum rules
  532. * - called when registering/choosing a password.
  533. * - checks the password obeys the current forum settings for password strength.
  534. * - if password checking is enabled, will check that none of the words in restrict_in appear in the password.
  535. * - returns an error identifier if the password is invalid, or null.
  536. *
  537. * @param string $password
  538. * @param string $username
  539. * @param array $restrict_in = array()
  540. * @return string an error identifier if the password is invalid
  541. */
  542. function validatePassword($password, $username, $restrict_in = array())
  543. {
  544. global $modSettings, $smcFunc;
  545. // Perform basic requirements first.
  546. if ($smcFunc['strlen']($password) < (empty($modSettings['password_strength']) ? 4 : 8))
  547. return 'short';
  548. // Is this enough?
  549. if (empty($modSettings['password_strength']))
  550. return null;
  551. // Otherwise, perform the medium strength test - checking if password appears in the restricted string.
  552. if (preg_match('~\b' . preg_quote($password, '~') . '\b~', implode(' ', $restrict_in)) != 0)
  553. return 'restricted_words';
  554. elseif ($smcFunc['strpos']($password, $username) !== false)
  555. return 'restricted_words';
  556. // If just medium, we're done.
  557. if ($modSettings['password_strength'] == 1)
  558. return null;
  559. // Otherwise, hard test next, check for numbers and letters, uppercase too.
  560. $good = preg_match('~(\D\d|\d\D)~', $password) != 0;
  561. $good &= $smcFunc['strtolower']($password) != $password;
  562. return $good ? null : 'chars';
  563. }
  564. /**
  565. * Quickly find out what moderation authority this user has
  566. * - builds the moderator, group and board level querys for the user
  567. * - stores the information on the current users moderation powers in $user_info['mod_cache'] and $_SESSION['mc']
  568. */
  569. function rebuildModCache()
  570. {
  571. global $user_info, $smcFunc;
  572. // What groups can they moderate?
  573. $group_query = allowedTo('manage_membergroups') ? '1=1' : '0=1';
  574. if ($group_query == '0=1')
  575. {
  576. $request = $smcFunc['db_query']('', '
  577. SELECT id_group
  578. FROM {db_prefix}group_moderators
  579. WHERE id_member = {int:current_member}',
  580. array(
  581. 'current_member' => $user_info['id'],
  582. )
  583. );
  584. $groups = array();
  585. while ($row = $smcFunc['db_fetch_assoc']($request))
  586. $groups[] = $row['id_group'];
  587. $smcFunc['db_free_result']($request);
  588. if (empty($groups))
  589. $group_query = '0=1';
  590. else
  591. $group_query = 'id_group IN (' . implode(',', $groups) . ')';
  592. }
  593. // Then, same again, just the boards this time!
  594. $board_query = allowedTo('moderate_forum') ? '1=1' : '0=1';
  595. if ($board_query == '0=1')
  596. {
  597. $boards = boardsAllowedTo('moderate_board', true);
  598. if (empty($boards))
  599. $board_query = '0=1';
  600. else
  601. $board_query = 'id_board IN (' . implode(',', $boards) . ')';
  602. }
  603. // What boards are they the moderator of?
  604. $boards_mod = array();
  605. if (!$user_info['is_guest'])
  606. {
  607. $request = $smcFunc['db_query']('', '
  608. SELECT id_board
  609. FROM {db_prefix}moderators
  610. WHERE id_member = {int:current_member}',
  611. array(
  612. 'current_member' => $user_info['id'],
  613. )
  614. );
  615. while ($row = $smcFunc['db_fetch_assoc']($request))
  616. $boards_mod[] = $row['id_board'];
  617. $smcFunc['db_free_result']($request);
  618. // Can any of the groups they're in moderate any of the boards?
  619. $request = $smcFunc['db_query']('', '
  620. SELECT id_board
  621. FROM {db_prefix}moderator_groups
  622. WHERE id_group IN({array_int:groups})',
  623. array(
  624. 'groups' => $user_info['groups'],
  625. )
  626. );
  627. while ($row = $smcFunc['db_fetch_assoc']($request))
  628. $boards_mod[] = $row['id_board'];
  629. $smcFunc['db_free_result']($request);
  630. // Just in case we've got duplicates here...
  631. $boards_mod = array_unique($boards_mod);
  632. }
  633. $mod_query = empty($boards_mod) ? '0=1' : 'b.id_board IN (' . implode(',', $boards_mod) . ')';
  634. $_SESSION['mc'] = array(
  635. 'time' => time(),
  636. // This looks a bit funny but protects against the login redirect.
  637. 'id' => $user_info['id'] && $user_info['name'] ? $user_info['id'] : 0,
  638. // If you change the format of 'gq' and/or 'bq' make sure to adjust 'can_mod' in Load.php.
  639. 'gq' => $group_query,
  640. 'bq' => $board_query,
  641. 'ap' => boardsAllowedTo('approve_posts'),
  642. 'mb' => $boards_mod,
  643. 'mq' => $mod_query,
  644. );
  645. call_integration_hook('integrate_mod_cache');
  646. $user_info['mod_cache'] = $_SESSION['mc'];
  647. // Might as well clean up some tokens while we are at it.
  648. cleanTokens();
  649. }
  650. /**
  651. * The same thing as setcookie but gives support for HTTP-Only cookies in PHP < 5.2
  652. *
  653. * @param string $name
  654. * @param string $value = ''
  655. * @param int $expire = 0
  656. * @param string $path = ''
  657. * @param string $domain = ''
  658. * @param bool $secure = false
  659. * @param bool $httponly = null
  660. */
  661. function smf_setcookie($name, $value = '', $expire = 0, $path = '', $domain = '', $secure = null, $httponly = null)
  662. {
  663. global $modSettings;
  664. // In case a customization wants to override the default settings
  665. if ($httponly === null)
  666. $httponly = !empty($modSettings['httponlyCookies']);
  667. if ($secure === null)
  668. $secure = !empty($modSettings['secureCookies']);
  669. // Intercept cookie?
  670. call_integration_hook('integrate_cookie', array($name, $value, $expire, $path, $domain, $secure, $httponly));
  671. // This function is pointless if we have PHP >= 5.2.
  672. if (version_compare(PHP_VERSION, '5.2', '>='))
  673. return setcookie($name, $value, $expire, $path, $domain, $secure, $httponly);
  674. // $httponly is the only reason I made this function. If it's not being used, use setcookie().
  675. if (!$httponly)
  676. return setcookie($name, $value, $expire, $path, $domain, $secure);
  677. // Ugh, looks like we have to resort to using a manual process.
  678. header('Set-Cookie: '.rawurlencode($name).'='.rawurlencode($value)
  679. .(empty($domain) ? '' : '; Domain='.$domain)
  680. .(empty($expire) ? '' : '; Max-Age='.$expire)
  681. .(empty($path) ? '' : '; Path='.$path)
  682. .(!$secure ? '' : '; Secure')
  683. .(!$httponly ? '' : '; HttpOnly'), false);
  684. }
  685. ?>