2
0

Subs-Auth.php 27 KB

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