Subs-Auth.php 27 KB

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