Subs-Members.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. <?php
  2. /**
  3. * This file contains some useful functions for members and membergroups.
  4. *
  5. * Simple Machines Forum (SMF)
  6. *
  7. * @package SMF
  8. * @author Simple Machines http://www.simplemachines.org
  9. * @copyright 2013 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. * Delete one or more members.
  18. * Requires profile_remove_own or profile_remove_any permission for
  19. * respectively removing your own account or any account.
  20. * Non-admins cannot delete admins.
  21. * The function:
  22. * - changes author of messages, topics and polls to guest authors.
  23. * - removes all log entries concerning the deleted members, except the
  24. * error logs, ban logs and moderation logs.
  25. * - removes these members' personal messages (only the inbox), avatars,
  26. * ban entries, theme settings, moderator positions, poll votes, and
  27. * karma votes.
  28. * - updates member statistics afterwards.
  29. *
  30. * @param array $users
  31. * @param bool $check_not_admin = false
  32. */
  33. function deleteMembers($users, $check_not_admin = false)
  34. {
  35. global $sourcedir, $modSettings, $user_info, $smcFunc;
  36. // Try give us a while to sort this out...
  37. @set_time_limit(600);
  38. // Try to get some more memory.
  39. setMemoryLimit('128M');
  40. // If it's not an array, make it so!
  41. if (!is_array($users))
  42. $users = array($users);
  43. else
  44. $users = array_unique($users);
  45. // Make sure there's no void user in here.
  46. $users = array_diff($users, array(0));
  47. // How many are they deleting?
  48. if (empty($users))
  49. return;
  50. elseif (count($users) == 1)
  51. {
  52. list ($user) = $users;
  53. if ($user == $user_info['id'])
  54. isAllowedTo('profile_remove_own');
  55. else
  56. isAllowedTo('profile_remove_any');
  57. }
  58. else
  59. {
  60. foreach ($users as $k => $v)
  61. $users[$k] = (int) $v;
  62. // Deleting more than one? You can't have more than one account...
  63. isAllowedTo('profile_remove_any');
  64. }
  65. // Get their names for logging purposes.
  66. $request = $smcFunc['db_query']('', '
  67. SELECT id_member, member_name, CASE WHEN id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0 THEN 1 ELSE 0 END AS is_admin
  68. FROM {db_prefix}members
  69. WHERE id_member IN ({array_int:user_list})
  70. LIMIT ' . count($users),
  71. array(
  72. 'user_list' => $users,
  73. 'admin_group' => 1,
  74. )
  75. );
  76. $admins = array();
  77. $user_log_details = array();
  78. while ($row = $smcFunc['db_fetch_assoc']($request))
  79. {
  80. if ($row['is_admin'])
  81. $admins[] = $row['id_member'];
  82. $user_log_details[$row['id_member']] = array($row['id_member'], $row['member_name']);
  83. }
  84. $smcFunc['db_free_result']($request);
  85. if (empty($user_log_details))
  86. return;
  87. // Make sure they aren't trying to delete administrators if they aren't one. But don't bother checking if it's just themself.
  88. if (!empty($admins) && ($check_not_admin || (!allowedTo('admin_forum') && (count($users) != 1 || $users[0] != $user_info['id']))))
  89. {
  90. $users = array_diff($users, $admins);
  91. foreach ($admins as $id)
  92. unset($user_log_details[$id]);
  93. }
  94. // No one left?
  95. if (empty($users))
  96. return;
  97. // Log the action - regardless of who is deleting it.
  98. $log_changes = array();
  99. foreach ($user_log_details as $user)
  100. {
  101. $log_changes[] = array(
  102. 'action' => 'delete_member',
  103. 'log_type' => 'admin',
  104. 'extra' => array(
  105. 'member' => $user[0],
  106. 'name' => $user[1],
  107. 'member_acted' => $user_info['name'],
  108. ),
  109. );
  110. // Remove any cached data if enabled.
  111. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  112. cache_put_data('user_settings-' . $user[0], null, 60);
  113. }
  114. // Make these peoples' posts guest posts.
  115. $smcFunc['db_query']('', '
  116. UPDATE {db_prefix}messages
  117. SET id_member = {int:guest_id}' . (!empty($modSettings['deleteMembersRemovesEmail']) ? ',
  118. poster_email = {string:blank_email}' : '') . '
  119. WHERE id_member IN ({array_int:users})',
  120. array(
  121. 'guest_id' => 0,
  122. 'blank_email' => '',
  123. 'users' => $users,
  124. )
  125. );
  126. $smcFunc['db_query']('', '
  127. UPDATE {db_prefix}polls
  128. SET id_member = {int:guest_id}
  129. WHERE id_member IN ({array_int:users})',
  130. array(
  131. 'guest_id' => 0,
  132. 'users' => $users,
  133. )
  134. );
  135. // Make these peoples' posts guest first posts and last posts.
  136. $smcFunc['db_query']('', '
  137. UPDATE {db_prefix}topics
  138. SET id_member_started = {int:guest_id}
  139. WHERE id_member_started IN ({array_int:users})',
  140. array(
  141. 'guest_id' => 0,
  142. 'users' => $users,
  143. )
  144. );
  145. $smcFunc['db_query']('', '
  146. UPDATE {db_prefix}topics
  147. SET id_member_updated = {int:guest_id}
  148. WHERE id_member_updated IN ({array_int:users})',
  149. array(
  150. 'guest_id' => 0,
  151. 'users' => $users,
  152. )
  153. );
  154. $smcFunc['db_query']('', '
  155. UPDATE {db_prefix}log_actions
  156. SET id_member = {int:guest_id}
  157. WHERE id_member IN ({array_int:users})',
  158. array(
  159. 'guest_id' => 0,
  160. 'users' => $users,
  161. )
  162. );
  163. $smcFunc['db_query']('', '
  164. UPDATE {db_prefix}log_banned
  165. SET id_member = {int:guest_id}
  166. WHERE id_member IN ({array_int:users})',
  167. array(
  168. 'guest_id' => 0,
  169. 'users' => $users,
  170. )
  171. );
  172. $smcFunc['db_query']('', '
  173. UPDATE {db_prefix}log_errors
  174. SET id_member = {int:guest_id}
  175. WHERE id_member IN ({array_int:users})',
  176. array(
  177. 'guest_id' => 0,
  178. 'users' => $users,
  179. )
  180. );
  181. // Delete the member.
  182. $smcFunc['db_query']('', '
  183. DELETE FROM {db_prefix}members
  184. WHERE id_member IN ({array_int:users})',
  185. array(
  186. 'users' => $users,
  187. )
  188. );
  189. // Delete any drafts...
  190. $smcFunc['db_query']('', '
  191. DELETE FROM {db_prefix}user_drafts
  192. WHERE id_member IN ({array_int:users})',
  193. array(
  194. 'users' => $users,
  195. )
  196. );
  197. // Delete the logs...
  198. $smcFunc['db_query']('', '
  199. DELETE FROM {db_prefix}log_actions
  200. WHERE id_log = {int:log_type}
  201. AND id_member IN ({array_int:users})',
  202. array(
  203. 'log_type' => 2,
  204. 'users' => $users,
  205. )
  206. );
  207. $smcFunc['db_query']('', '
  208. DELETE FROM {db_prefix}log_boards
  209. WHERE id_member IN ({array_int:users})',
  210. array(
  211. 'users' => $users,
  212. )
  213. );
  214. $smcFunc['db_query']('', '
  215. DELETE FROM {db_prefix}log_comments
  216. WHERE id_recipient IN ({array_int:users})
  217. AND comment_type = {string:warntpl}',
  218. array(
  219. 'users' => $users,
  220. 'warntpl' => 'warntpl',
  221. )
  222. );
  223. $smcFunc['db_query']('', '
  224. DELETE FROM {db_prefix}log_group_requests
  225. WHERE id_member IN ({array_int:users})',
  226. array(
  227. 'users' => $users,
  228. )
  229. );
  230. $smcFunc['db_query']('', '
  231. DELETE FROM {db_prefix}log_karma
  232. WHERE id_target IN ({array_int:users})
  233. OR id_executor IN ({array_int:users})',
  234. array(
  235. 'users' => $users,
  236. )
  237. );
  238. $smcFunc['db_query']('', '
  239. DELETE FROM {db_prefix}log_mark_read
  240. WHERE id_member IN ({array_int:users})',
  241. array(
  242. 'users' => $users,
  243. )
  244. );
  245. $smcFunc['db_query']('', '
  246. DELETE FROM {db_prefix}log_notify
  247. WHERE id_member IN ({array_int:users})',
  248. array(
  249. 'users' => $users,
  250. )
  251. );
  252. $smcFunc['db_query']('', '
  253. DELETE FROM {db_prefix}log_online
  254. WHERE id_member IN ({array_int:users})',
  255. array(
  256. 'users' => $users,
  257. )
  258. );
  259. $smcFunc['db_query']('', '
  260. DELETE FROM {db_prefix}log_subscribed
  261. WHERE id_member IN ({array_int:users})',
  262. array(
  263. 'users' => $users,
  264. )
  265. );
  266. $smcFunc['db_query']('', '
  267. DELETE FROM {db_prefix}log_topics
  268. WHERE id_member IN ({array_int:users})',
  269. array(
  270. 'users' => $users,
  271. )
  272. );
  273. $smcFunc['db_query']('', '
  274. DELETE FROM {db_prefix}collapsed_categories
  275. WHERE id_member IN ({array_int:users})',
  276. array(
  277. 'users' => $users,
  278. )
  279. );
  280. // Make their votes appear as guest votes - at least it keeps the totals right.
  281. // @todo Consider adding back in cookie protection.
  282. $smcFunc['db_query']('', '
  283. UPDATE {db_prefix}log_polls
  284. SET id_member = {int:guest_id}
  285. WHERE id_member IN ({array_int:users})',
  286. array(
  287. 'guest_id' => 0,
  288. 'users' => $users,
  289. )
  290. );
  291. // Delete personal messages.
  292. require_once($sourcedir . '/PersonalMessage.php');
  293. deleteMessages(null, null, $users);
  294. $smcFunc['db_query']('', '
  295. UPDATE {db_prefix}personal_messages
  296. SET id_member_from = {int:guest_id}
  297. WHERE id_member_from IN ({array_int:users})',
  298. array(
  299. 'guest_id' => 0,
  300. 'users' => $users,
  301. )
  302. );
  303. // They no longer exist, so we don't know who it was sent to.
  304. $smcFunc['db_query']('', '
  305. DELETE FROM {db_prefix}pm_recipients
  306. WHERE id_member IN ({array_int:users})',
  307. array(
  308. 'users' => $users,
  309. )
  310. );
  311. // Delete avatar.
  312. require_once($sourcedir . '/ManageAttachments.php');
  313. removeAttachments(array('id_member' => $users));
  314. // It's over, no more moderation for you.
  315. $smcFunc['db_query']('', '
  316. DELETE FROM {db_prefix}moderators
  317. WHERE id_member IN ({array_int:users})',
  318. array(
  319. 'users' => $users,
  320. )
  321. );
  322. $smcFunc['db_query']('', '
  323. DELETE FROM {db_prefix}group_moderators
  324. WHERE id_member IN ({array_int:users})',
  325. array(
  326. 'users' => $users,
  327. )
  328. );
  329. // If you don't exist we can't ban you.
  330. $smcFunc['db_query']('', '
  331. DELETE FROM {db_prefix}ban_items
  332. WHERE id_member IN ({array_int:users})',
  333. array(
  334. 'users' => $users,
  335. )
  336. );
  337. // Remove individual theme settings.
  338. $smcFunc['db_query']('', '
  339. DELETE FROM {db_prefix}themes
  340. WHERE id_member IN ({array_int:users})',
  341. array(
  342. 'users' => $users,
  343. )
  344. );
  345. // These users are nobody's buddy nomore.
  346. $request = $smcFunc['db_query']('', '
  347. SELECT id_member, pm_ignore_list, buddy_list
  348. FROM {db_prefix}members
  349. WHERE FIND_IN_SET({raw:pm_ignore_list}, pm_ignore_list) != 0 OR FIND_IN_SET({raw:buddy_list}, buddy_list) != 0',
  350. array(
  351. 'pm_ignore_list' => implode(', pm_ignore_list) != 0 OR FIND_IN_SET(', $users),
  352. 'buddy_list' => implode(', buddy_list) != 0 OR FIND_IN_SET(', $users),
  353. )
  354. );
  355. while ($row = $smcFunc['db_fetch_assoc']($request))
  356. $smcFunc['db_query']('', '
  357. UPDATE {db_prefix}members
  358. SET
  359. pm_ignore_list = {string:pm_ignore_list},
  360. buddy_list = {string:buddy_list}
  361. WHERE id_member = {int:id_member}',
  362. array(
  363. 'id_member' => $row['id_member'],
  364. 'pm_ignore_list' => implode(',', array_diff(explode(',', $row['pm_ignore_list']), $users)),
  365. 'buddy_list' => implode(',', array_diff(explode(',', $row['buddy_list']), $users)),
  366. )
  367. );
  368. $smcFunc['db_free_result']($request);
  369. // Make sure no member's birthday is still sticking in the calendar...
  370. updateSettings(array(
  371. 'calendar_updated' => time(),
  372. ));
  373. // Integration rocks!
  374. call_integration_hook('integrate_delete_members', array($users));
  375. updateStats('member');
  376. require_once($sourcedir . '/Logging.php');
  377. logActions($log_changes);
  378. }
  379. /**
  380. * Registers a member to the forum.
  381. * Allows two types of interface: 'guest' and 'admin'. The first
  382. * includes hammering protection, the latter can perform the
  383. * registration silently.
  384. * The strings used in the options array are assumed to be escaped.
  385. * Allows to perform several checks on the input, e.g. reserved names.
  386. * The function will adjust member statistics.
  387. * If an error is detected will fatal error on all errors unless return_errors is true.
  388. *
  389. * @param array $regOptions
  390. * @param bool $return_errors - specify whether to return the errors
  391. * @return int, the ID of the newly created member
  392. */
  393. function registerMember(&$regOptions, $return_errors = false)
  394. {
  395. global $scripturl, $txt, $modSettings, $context, $sourcedir;
  396. global $user_info, $options, $settings, $smcFunc;
  397. loadLanguage('Login');
  398. // We'll need some external functions.
  399. require_once($sourcedir . '/Subs-Auth.php');
  400. require_once($sourcedir . '/Subs-Post.php');
  401. // Put any errors in here.
  402. $reg_errors = array();
  403. // Registration from the admin center, let them sweat a little more.
  404. if ($regOptions['interface'] == 'admin')
  405. {
  406. is_not_guest();
  407. isAllowedTo('moderate_forum');
  408. }
  409. // If you're an admin, you're special ;).
  410. elseif ($regOptions['interface'] == 'guest')
  411. {
  412. // You cannot register twice...
  413. if (empty($user_info['is_guest']))
  414. redirectexit();
  415. // Make sure they didn't just register with this session.
  416. if (!empty($_SESSION['just_registered']) && empty($modSettings['disableRegisterCheck']))
  417. fatal_lang_error('register_only_once', false);
  418. }
  419. // What method of authorization are we going to use?
  420. if (empty($regOptions['auth_method']) || !in_array($regOptions['auth_method'], array('password', 'openid')))
  421. {
  422. if (!empty($regOptions['openid']))
  423. $regOptions['auth_method'] = 'openid';
  424. else
  425. $regOptions['auth_method'] = 'password';
  426. }
  427. // Spaces and other odd characters are evil...
  428. $regOptions['username'] = trim(preg_replace('~[\t\n\r \x0B\0' . ($context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : "\xC2\xA0\xC2\xAD\xE2\x80\x80-\xE2\x80\x8F\xE2\x80\x9F\xE2\x80\xAF\xE2\x80\x9F\xE3\x80\x80\xEF\xBB\xBF") : '\x00-\x08\x0B\x0C\x0E-\x19\xA0') . ']+~' . ($context['utf8'] ? 'u' : ''), ' ', $regOptions['username']));
  429. // @todo Separate the sprintf?
  430. if (empty($regOptions['email']) || preg_match('~^[0-9A-Za-z=_+\-/][0-9A-Za-z=_\'+\-/\.]*@[\w\-]+(\.[\w\-]+)*(\.[\w]{2,6})$~', $regOptions['email']) === 0 || strlen($regOptions['email']) > 255)
  431. $reg_errors[] = array('lang', 'profile_error_bad_email');
  432. $username_validation_errors = validateUsername(0, $regOptions['username'], true, !empty($regOptions['check_reserved_name']));
  433. if (!empty($username_validation_errors))
  434. $reg_errors = array_merge($reg_errors, $username_validation_errors);
  435. // Generate a validation code if it's supposed to be emailed.
  436. $validation_code = '';
  437. if ($regOptions['require'] == 'activation')
  438. $validation_code = generateValidationCode();
  439. // If you haven't put in a password generate one.
  440. if ($regOptions['interface'] == 'admin' && $regOptions['password'] == '' && $regOptions['auth_method'] == 'password')
  441. {
  442. mt_srand(time() + 1277);
  443. $regOptions['password'] = generateValidationCode();
  444. $regOptions['password_check'] = $regOptions['password'];
  445. }
  446. // Does the first password match the second?
  447. elseif ($regOptions['password'] != $regOptions['password_check'] && $regOptions['auth_method'] == 'password')
  448. $reg_errors[] = array('lang', 'passwords_dont_match');
  449. // That's kind of easy to guess...
  450. if ($regOptions['password'] == '')
  451. {
  452. if ($regOptions['auth_method'] == 'password')
  453. $reg_errors[] = array('lang', 'no_password');
  454. else
  455. $regOptions['password'] = sha1(mt_rand());
  456. }
  457. // Now perform hard password validation as required.
  458. if (!empty($regOptions['check_password_strength']) && $regOptions['password'] != '')
  459. {
  460. $passwordError = validatePassword($regOptions['password'], $regOptions['username'], array($regOptions['email']));
  461. // Password isn't legal?
  462. if ($passwordError != null)
  463. $reg_errors[] = array('lang', 'profile_error_password_' . $passwordError);
  464. }
  465. // If they are using an OpenID that hasn't been verified yet error out.
  466. // @todo Change this so they can register without having to attempt a login first
  467. if ($regOptions['auth_method'] == 'openid' && (empty($_SESSION['openid']['verified']) || $_SESSION['openid']['openid_uri'] != $regOptions['openid']))
  468. $reg_errors[] = array('lang', 'openid_not_verified');
  469. // You may not be allowed to register this email.
  470. if (!empty($regOptions['check_email_ban']))
  471. isBannedEmail($regOptions['email'], 'cannot_register', $txt['ban_register_prohibited']);
  472. // Check if the email address is in use.
  473. $request = $smcFunc['db_query']('', '
  474. SELECT id_member
  475. FROM {db_prefix}members
  476. WHERE email_address = {string:email_address}
  477. OR email_address = {string:username}
  478. LIMIT 1',
  479. array(
  480. 'email_address' => $regOptions['email'],
  481. 'username' => $regOptions['username'],
  482. )
  483. );
  484. // @todo Separate the sprintf?
  485. if ($smcFunc['db_num_rows']($request) != 0)
  486. $reg_errors[] = array('lang', 'email_in_use', false, array(htmlspecialchars($regOptions['email'])));
  487. $smcFunc['db_free_result']($request);
  488. // Perhaps someone else wants to check this user
  489. call_integration_hook('integrate_register_check', array(&$regOptions, &$reg_errors));
  490. // If we found any errors we need to do something about it right away!
  491. foreach ($reg_errors as $key => $error)
  492. {
  493. /* Note for each error:
  494. 0 = 'lang' if it's an index, 'done' if it's clear text.
  495. 1 = The text/index.
  496. 2 = Whether to log.
  497. 3 = sprintf data if necessary. */
  498. if ($error[0] == 'lang')
  499. loadLanguage('Errors');
  500. $message = $error[0] == 'lang' ? (empty($error[3]) ? $txt[$error[1]] : vsprintf($txt[$error[1]], $error[3])) : $error[1];
  501. // What to do, what to do, what to do.
  502. if ($return_errors)
  503. {
  504. if (!empty($error[2]))
  505. log_error($message, $error[2]);
  506. $reg_errors[$key] = $message;
  507. }
  508. else
  509. fatal_error($message, empty($error[2]) ? false : $error[2]);
  510. }
  511. // If there's any errors left return them at once!
  512. if (!empty($reg_errors))
  513. return $reg_errors;
  514. $reservedVars = array(
  515. 'actual_theme_url',
  516. 'actual_images_url',
  517. 'base_theme_dir',
  518. 'base_theme_url',
  519. 'default_images_url',
  520. 'default_theme_dir',
  521. 'default_theme_url',
  522. 'default_template',
  523. 'images_url',
  524. 'number_recent_posts',
  525. 'smiley_sets_default',
  526. 'theme_dir',
  527. 'theme_id',
  528. 'theme_layers',
  529. 'theme_templates',
  530. 'theme_url',
  531. );
  532. // Can't change reserved vars.
  533. if (isset($regOptions['theme_vars']) && count(array_intersect(array_keys($regOptions['theme_vars']), $reservedVars)) != 0)
  534. fatal_lang_error('no_theme');
  535. // Some of these might be overwritten. (the lower ones that are in the arrays below.)
  536. $regOptions['register_vars'] = array(
  537. 'member_name' => $regOptions['username'],
  538. 'email_address' => $regOptions['email'],
  539. 'passwd' => sha1(strtolower($regOptions['username']) . $regOptions['password']),
  540. 'password_salt' => substr(md5(mt_rand()), 0, 4) ,
  541. 'posts' => 0,
  542. 'date_registered' => time(),
  543. 'member_ip' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $user_info['ip'],
  544. 'member_ip2' => $regOptions['interface'] == 'admin' ? '127.0.0.1' : $_SERVER['BAN_CHECK_IP'],
  545. 'validation_code' => $validation_code,
  546. 'real_name' => $regOptions['username'],
  547. 'personal_text' => $modSettings['default_personal_text'],
  548. 'pm_email_notify' => 1,
  549. 'id_theme' => 0,
  550. 'id_post_group' => 4,
  551. 'lngfile' => '',
  552. 'buddy_list' => '',
  553. 'pm_ignore_list' => '',
  554. 'message_labels' => '',
  555. 'website_title' => '',
  556. 'website_url' => '',
  557. 'location' => '',
  558. 'icq' => '',
  559. 'aim' => '',
  560. 'yim' => '',
  561. 'skype' => '',
  562. 'time_format' => '',
  563. 'signature' => '',
  564. 'avatar' => '',
  565. 'usertitle' => '',
  566. 'secret_question' => '',
  567. 'secret_answer' => '',
  568. 'additional_groups' => '',
  569. 'ignore_boards' => '',
  570. 'smiley_set' => '',
  571. 'openid_uri' => (!empty($regOptions['openid']) ? $regOptions['openid'] : ''),
  572. );
  573. // Setup the activation status on this new account so it is correct - firstly is it an under age account?
  574. if ($regOptions['require'] == 'coppa')
  575. {
  576. $regOptions['register_vars']['is_activated'] = 5;
  577. // @todo This should be changed. To what should be it be changed??
  578. $regOptions['register_vars']['validation_code'] = '';
  579. }
  580. // Maybe it can be activated right away?
  581. elseif ($regOptions['require'] == 'nothing')
  582. $regOptions['register_vars']['is_activated'] = 1;
  583. // Maybe it must be activated by email?
  584. elseif ($regOptions['require'] == 'activation')
  585. $regOptions['register_vars']['is_activated'] = 0;
  586. // Otherwise it must be awaiting approval!
  587. else
  588. $regOptions['register_vars']['is_activated'] = 3;
  589. if (isset($regOptions['memberGroup']))
  590. {
  591. // Make sure the id_group will be valid, if this is an administator.
  592. $regOptions['register_vars']['id_group'] = $regOptions['memberGroup'] == 1 && !allowedTo('admin_forum') ? 0 : $regOptions['memberGroup'];
  593. // Check if this group is assignable.
  594. $unassignableGroups = array(-1, 3);
  595. $request = $smcFunc['db_query']('', '
  596. SELECT id_group
  597. FROM {db_prefix}membergroups
  598. WHERE min_posts != {int:min_posts}' . (allowedTo('admin_forum') ? '' : '
  599. OR group_type = {int:is_protected}'),
  600. array(
  601. 'min_posts' => -1,
  602. 'is_protected' => 1,
  603. )
  604. );
  605. while ($row = $smcFunc['db_fetch_assoc']($request))
  606. $unassignableGroups[] = $row['id_group'];
  607. $smcFunc['db_free_result']($request);
  608. if (in_array($regOptions['register_vars']['id_group'], $unassignableGroups))
  609. $regOptions['register_vars']['id_group'] = 0;
  610. }
  611. // ICQ cannot be zero.
  612. if (isset($regOptions['extra_register_vars']['icq']) && empty($regOptions['extra_register_vars']['icq']))
  613. $regOptions['extra_register_vars']['icq'] = '';
  614. // Integrate optional member settings to be set.
  615. if (!empty($regOptions['extra_register_vars']))
  616. foreach ($regOptions['extra_register_vars'] as $var => $value)
  617. $regOptions['register_vars'][$var] = $value;
  618. // Integrate optional user theme options to be set.
  619. $theme_vars = array();
  620. if (!empty($regOptions['theme_vars']))
  621. foreach ($regOptions['theme_vars'] as $var => $value)
  622. $theme_vars[$var] = $value;
  623. // Right, now let's prepare for insertion.
  624. $knownInts = array(
  625. 'date_registered', 'posts', 'id_group', 'last_login', 'instant_messages', 'unread_messages',
  626. 'new_pm', 'pm_prefs', 'gender', 'hide_email', 'show_online', 'pm_email_notify', 'karma_good', 'karma_bad',
  627. 'notify_announcements', 'notify_send_body', 'notify_regularity', 'notify_types',
  628. 'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning',
  629. );
  630. $knownFloats = array(
  631. 'time_offset',
  632. );
  633. // Call an optional function to validate the users' input.
  634. call_integration_hook('integrate_register', array(&$regOptions, &$theme_vars, &$knownInts, &$knownFloats));
  635. $column_names = array();
  636. $values = array();
  637. foreach ($regOptions['register_vars'] as $var => $val)
  638. {
  639. $type = 'string';
  640. if (in_array($var, $knownInts))
  641. $type = 'int';
  642. elseif (in_array($var, $knownFloats))
  643. $type = 'float';
  644. elseif ($var == 'birthdate')
  645. $type = 'date';
  646. $column_names[$var] = $type;
  647. $values[$var] = $val;
  648. }
  649. // Register them into the database.
  650. $smcFunc['db_insert']('',
  651. '{db_prefix}members',
  652. $column_names,
  653. $values,
  654. array('id_member')
  655. );
  656. $memberID = $smcFunc['db_insert_id']('{db_prefix}members', 'id_member');
  657. // Call an optional function as notification of registration.
  658. call_integration_hook('integrate_post_register', array(&$regOptions, &$theme_vars, &$memberID));
  659. // Update the number of members and latest member's info - and pass the name, but remove the 's.
  660. if ($regOptions['register_vars']['is_activated'] == 1)
  661. updateStats('member', $memberID, $regOptions['register_vars']['real_name']);
  662. else
  663. updateStats('member');
  664. // Theme variables too?
  665. if (!empty($theme_vars))
  666. {
  667. $inserts = array();
  668. foreach ($theme_vars as $var => $val)
  669. $inserts[] = array($memberID, $var, $val);
  670. $smcFunc['db_insert']('insert',
  671. '{db_prefix}themes',
  672. array('id_member' => 'int', 'variable' => 'string-255', 'value' => 'string-65534'),
  673. $inserts,
  674. array('id_member', 'variable')
  675. );
  676. }
  677. // If it's enabled, increase the registrations for today.
  678. trackStats(array('registers' => '+'));
  679. // Administrative registrations are a bit different...
  680. if ($regOptions['interface'] == 'admin')
  681. {
  682. if ($regOptions['require'] == 'activation')
  683. $email_message = 'admin_register_activate';
  684. elseif (!empty($regOptions['send_welcome_email']))
  685. $email_message = 'admin_register_immediate';
  686. if (isset($email_message))
  687. {
  688. $replacements = array(
  689. 'REALNAME' => $regOptions['register_vars']['real_name'],
  690. 'USERNAME' => $regOptions['username'],
  691. 'PASSWORD' => $regOptions['password'],
  692. 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
  693. 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code,
  694. 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID,
  695. 'ACTIVATIONCODE' => $validation_code,
  696. );
  697. $emaildata = loadEmailTemplate($email_message, $replacements);
  698. sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
  699. }
  700. // All admins are finished here.
  701. return $memberID;
  702. }
  703. // Can post straight away - welcome them to your fantastic community...
  704. if ($regOptions['require'] == 'nothing')
  705. {
  706. if (!empty($regOptions['send_welcome_email']))
  707. {
  708. $replacements = array(
  709. 'REALNAME' => $regOptions['register_vars']['real_name'],
  710. 'USERNAME' => $regOptions['username'],
  711. 'PASSWORD' => $regOptions['password'],
  712. 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
  713. 'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : '',
  714. );
  715. $emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . 'immediate', $replacements);
  716. sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
  717. }
  718. // Send admin their notification.
  719. adminNotify('standard', $memberID, $regOptions['username']);
  720. }
  721. // Need to activate their account - or fall under COPPA.
  722. elseif ($regOptions['require'] == 'activation' || $regOptions['require'] == 'coppa')
  723. {
  724. $replacements = array(
  725. 'REALNAME' => $regOptions['register_vars']['real_name'],
  726. 'USERNAME' => $regOptions['username'],
  727. 'PASSWORD' => $regOptions['password'],
  728. 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
  729. 'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : '',
  730. );
  731. if ($regOptions['require'] == 'activation')
  732. $replacements += array(
  733. 'ACTIVATIONLINK' => $scripturl . '?action=activate;u=' . $memberID . ';code=' . $validation_code,
  734. 'ACTIVATIONLINKWITHOUTCODE' => $scripturl . '?action=activate;u=' . $memberID,
  735. 'ACTIVATIONCODE' => $validation_code,
  736. );
  737. else
  738. $replacements += array(
  739. 'COPPALINK' => $scripturl . '?action=coppa;u=' . $memberID,
  740. );
  741. $emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . ($regOptions['require'] == 'activation' ? 'activate' : 'coppa'), $replacements);
  742. sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
  743. }
  744. // Must be awaiting approval.
  745. else
  746. {
  747. $replacements = array(
  748. 'REALNAME' => $regOptions['register_vars']['real_name'],
  749. 'USERNAME' => $regOptions['username'],
  750. 'PASSWORD' => $regOptions['password'],
  751. 'FORGOTPASSWORDLINK' => $scripturl . '?action=reminder',
  752. 'OPENID' => !empty($regOptions['openid']) ? $regOptions['openid'] : '',
  753. );
  754. $emaildata = loadEmailTemplate('register_' . ($regOptions['auth_method'] == 'openid' ? 'openid_' : '') . 'pending', $replacements);
  755. sendmail($regOptions['email'], $emaildata['subject'], $emaildata['body'], null, null, false, 0);
  756. // Admin gets informed here...
  757. adminNotify('approval', $memberID, $regOptions['username']);
  758. }
  759. // Okay, they're for sure registered... make sure the session is aware of this for security. (Just married :P!)
  760. $_SESSION['just_registered'] = 1;
  761. // If they are for sure registered, let other people to know about it
  762. call_integration_hook('integrate_register_after', array($regOptions, $memberID));
  763. return $memberID;
  764. }
  765. /**
  766. * Check if a name is in the reserved words list.
  767. * (name, current member id, name/username?.)
  768. * - checks if name is a reserved name or username.
  769. * - if is_name is false, the name is assumed to be a username.
  770. * - the id_member variable is used to ignore duplicate matches with the
  771. * current member.
  772. *
  773. * @param string $name
  774. * @param int $current_ID_MEMBER
  775. * @param bool $is_name
  776. * @param bool $fatal
  777. */
  778. function isReservedName($name, $current_ID_MEMBER = 0, $is_name = true, $fatal = true)
  779. {
  780. global $user_info, $modSettings, $smcFunc, $context;
  781. $name = preg_replace_callback('~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'replaceEntities__callback', $name);
  782. $checkName = $smcFunc['strtolower']($name);
  783. // Administrators are never restricted ;).
  784. if (!allowedTo('moderate_forum') && ((!empty($modSettings['reserveName']) && $is_name) || !empty($modSettings['reserveUser']) && !$is_name))
  785. {
  786. $reservedNames = explode("\n", $modSettings['reserveNames']);
  787. // Case sensitive check?
  788. $checkMe = empty($modSettings['reserveCase']) ? $checkName : $name;
  789. // Check each name in the list...
  790. foreach ($reservedNames as $reserved)
  791. {
  792. if ($reserved == '')
  793. continue;
  794. // The admin might've used entities too, level the playing field.
  795. $reservedCheck = preg_replace('~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~', 'replaceEntities__callback', $reserved);
  796. // Case sensitive name?
  797. if (empty($modSettings['reserveCase']))
  798. $reservedCheck = $smcFunc['strtolower']($reservedCheck);
  799. // If it's not just entire word, check for it in there somewhere...
  800. if ($checkMe == $reservedCheck || ($smcFunc['strpos']($checkMe, $reservedCheck) !== false && empty($modSettings['reserveWord'])))
  801. if ($fatal)
  802. fatal_lang_error('username_reserved', 'password', array($reserved));
  803. else
  804. return true;
  805. }
  806. $censor_name = $name;
  807. if (censorText($censor_name) != $name)
  808. if ($fatal)
  809. fatal_lang_error('name_censored', 'password', array($name));
  810. else
  811. return true;
  812. }
  813. // Characters we just shouldn't allow, regardless.
  814. foreach (array('*') as $char)
  815. if (strpos($checkName, $char) !== false)
  816. if ($fatal)
  817. fatal_lang_error('username_reserved', 'password', array($char));
  818. else
  819. return true;
  820. // Get rid of any SQL parts of the reserved name...
  821. $checkName = strtr($name, array('_' => '\\_', '%' => '\\%'));
  822. // Make sure they don't want someone else's name.
  823. $request = $smcFunc['db_query']('', '
  824. SELECT id_member
  825. FROM {db_prefix}members
  826. WHERE ' . (empty($current_ID_MEMBER) ? '' : 'id_member != {int:current_member}
  827. AND ') . '({raw:real_name} LIKE {string:check_name} OR {raw:member_name} LIKE {string:check_name})
  828. LIMIT 1',
  829. array(
  830. 'real_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(real_name)' : 'real_name',
  831. 'member_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(member_name)' : 'member_name',
  832. 'current_member' => $current_ID_MEMBER,
  833. 'check_name' => $checkName,
  834. )
  835. );
  836. if ($smcFunc['db_num_rows']($request) > 0)
  837. {
  838. $smcFunc['db_free_result']($request);
  839. return true;
  840. }
  841. // Does name case insensitive match a member group name?
  842. $request = $smcFunc['db_query']('', '
  843. SELECT id_group
  844. FROM {db_prefix}membergroups
  845. WHERE {raw:group_name} LIKE {string:check_name}
  846. LIMIT 1',
  847. array(
  848. 'group_name' => $smcFunc['db_case_sensitive'] ? 'LOWER(group_name)' : 'group_name',
  849. 'check_name' => $checkName,
  850. )
  851. );
  852. if ($smcFunc['db_num_rows']($request) > 0)
  853. {
  854. $smcFunc['db_free_result']($request);
  855. return true;
  856. }
  857. // Okay, they passed.
  858. return false;
  859. }
  860. // Get a list of groups that have a given permission (on a given board).
  861. /**
  862. * Retrieves a list of membergroups that are allowed to do the given
  863. * permission. (on the given board)
  864. * If board_id is not null, a board permission is assumed.
  865. * The function takes different permission settings into account.
  866. *
  867. * @param string $permission
  868. * @param int $board_id = null
  869. * @return an array containing an array for the allowed membergroup ID's
  870. * and an array for the denied membergroup ID's.
  871. */
  872. function groupsAllowedTo($permission, $board_id = null)
  873. {
  874. global $modSettings, $board_info, $smcFunc;
  875. // Admins are allowed to do anything.
  876. $member_groups = array(
  877. 'allowed' => array(1),
  878. 'denied' => array(),
  879. );
  880. // Assume we're dealing with regular permissions (like profile_view_own).
  881. if ($board_id === null)
  882. {
  883. $request = $smcFunc['db_query']('', '
  884. SELECT id_group, add_deny
  885. FROM {db_prefix}permissions
  886. WHERE permission = {string:permission}',
  887. array(
  888. 'permission' => $permission,
  889. )
  890. );
  891. while ($row = $smcFunc['db_fetch_assoc']($request))
  892. $member_groups[$row['add_deny'] === '1' ? 'allowed' : 'denied'][] = $row['id_group'];
  893. $smcFunc['db_free_result']($request);
  894. }
  895. // Otherwise it's time to look at the board.
  896. else
  897. {
  898. // First get the profile of the given board.
  899. if (isset($board_info['id']) && $board_info['id'] == $board_id)
  900. $profile_id = $board_info['profile'];
  901. elseif ($board_id !== 0)
  902. {
  903. $request = $smcFunc['db_query']('', '
  904. SELECT id_profile
  905. FROM {db_prefix}boards
  906. WHERE id_board = {int:id_board}
  907. LIMIT 1',
  908. array(
  909. 'id_board' => $board_id,
  910. )
  911. );
  912. if ($smcFunc['db_num_rows']($request) == 0)
  913. fatal_lang_error('no_board');
  914. list ($profile_id) = $smcFunc['db_fetch_row']($request);
  915. $smcFunc['db_free_result']($request);
  916. }
  917. else
  918. $profile_id = 1;
  919. $request = $smcFunc['db_query']('', '
  920. SELECT bp.id_group, bp.add_deny
  921. FROM {db_prefix}board_permissions AS bp
  922. WHERE bp.permission = {string:permission}
  923. AND bp.id_profile = {int:profile_id}',
  924. array(
  925. 'profile_id' => $profile_id,
  926. 'permission' => $permission,
  927. )
  928. );
  929. while ($row = $smcFunc['db_fetch_assoc']($request))
  930. $member_groups[$row['add_deny'] === '1' ? 'allowed' : 'denied'][] = $row['id_group'];
  931. $smcFunc['db_free_result']($request);
  932. $moderator_groups = array();
  933. // "Inherit" any moderator permissions as needed
  934. if (isset($board_info['moderator_groups']))
  935. {
  936. $moderator_groups = array_keys($board_info['moderator_groups']);
  937. }
  938. elseif ($board_id !== 0)
  939. {
  940. // Get the groups that can moderate this board
  941. $request = $smcFunc['db_query']('', '
  942. SELECT id_group
  943. FROM {db_prefix}moderator_groups
  944. WHERE id_board = {int:board_id}',
  945. array(
  946. 'board_id' => $board_id,
  947. )
  948. );
  949. while ($row = $smcFunc['db_fetch_assoc']($request))
  950. {
  951. $moderator_groups[] = $row['id_group'];
  952. }
  953. $smcFunc['db_free_result']($request);
  954. }
  955. // "Inherit" any additional permissions from the "Moderators" group
  956. foreach ($moderator_groups as $mod_group)
  957. {
  958. // If they're not specifically allowed, but the moderator group is, then allow it
  959. if (in_array(3, $member_groups['allowed']) && !in_array($mod_group, $member_groups['allowed']))
  960. {
  961. $member_groups['allowed'][] = $mod_group;
  962. }
  963. // They're not denied, but the moderator group is, so deny it
  964. if (in_array(3, $member_groups['denied']) && !in_array($mod_group, $member_groups['denied']))
  965. {
  966. $member_groups['denied'][] = $mod_group;
  967. }
  968. }
  969. }
  970. // Denied is never allowed.
  971. $member_groups['allowed'] = array_diff($member_groups['allowed'], $member_groups['denied']);
  972. return $member_groups;
  973. }
  974. /**
  975. * Retrieves a list of members that have a given permission
  976. * (on a given board).
  977. * If board_id is not null, a board permission is assumed.
  978. * Takes different permission settings into account.
  979. * Takes possible moderators (on board 'board_id') into account.
  980. *
  981. * @param string $permission
  982. * @param int $board_id = null
  983. * @return an array containing member ID's.
  984. */
  985. function membersAllowedTo($permission, $board_id = null)
  986. {
  987. global $smcFunc;
  988. $member_groups = groupsAllowedTo($permission, $board_id);
  989. $all_groups = array_merge($member_groups['allowed'], $member_groups['denied']);
  990. $include_moderators = in_array(3, $member_groups['allowed']) && $board_id !== null;
  991. $member_groups['allowed'] = array_diff($member_groups['allowed'], array(3));
  992. $exclude_moderators = in_array(3, $member_groups['denied']) && $board_id !== null;
  993. $member_groups['denied'] = array_diff($member_groups['denied'], array(3));
  994. $request = $smcFunc['db_query']('', '
  995. SELECT mem.id_member
  996. FROM {db_prefix}members AS mem' . ($include_moderators || $exclude_moderators ? '
  997. LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_member = mem.id_member AND mods.id_board = {int:board_id})
  998. LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_group IN ({array_int:all_member_groups}))' : '') . '
  999. WHERE (' . ($include_moderators ? 'mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR ' : '') . 'mem.id_group IN ({array_int:member_groups_allowed}) OR FIND_IN_SET({raw:member_group_allowed_implode}, mem.additional_groups) != 0 OR mem.id_post_group IN ({array_int:member_groups_allowed}))' . (empty($member_groups['denied']) ? '' : '
  1000. AND NOT (' . ($exclude_moderators ? 'mods.id_member IS NOT NULL OR modgs.id_group IS NOT NULL OR ' : '') . 'mem.id_group IN ({array_int:member_groups_denied}) OR FIND_IN_SET({raw:member_group_denied_implode}, mem.additional_groups) != 0 OR mem.id_post_group IN ({array_int:member_groups_denied}))'),
  1001. array(
  1002. 'member_groups_allowed' => $member_groups['allowed'],
  1003. 'member_groups_denied' => $member_groups['denied'],
  1004. 'all_member_groups' => $all_groups,
  1005. 'board_id' => $board_id,
  1006. 'member_group_allowed_implode' => implode(', mem.additional_groups) != 0 OR FIND_IN_SET(', $member_groups['allowed']),
  1007. 'member_group_denied_implode' => implode(', mem.additional_groups) != 0 OR FIND_IN_SET(', $member_groups['denied']),
  1008. )
  1009. );
  1010. $members = array();
  1011. while ($row = $smcFunc['db_fetch_assoc']($request))
  1012. $members[] = $row['id_member'];
  1013. $smcFunc['db_free_result']($request);
  1014. return $members;
  1015. }
  1016. /**
  1017. * This function is used to reassociate members with relevant posts.
  1018. * Reattribute guest posts to a specified member.
  1019. * Does not check for any permissions.
  1020. * If add_to_post_count is set, the member's post count is increased.
  1021. *
  1022. * @param int $memID
  1023. * @param string $email = false
  1024. * @param string $membername = false
  1025. * @param bool $post_count = false
  1026. * @return nothing
  1027. */
  1028. function reattributePosts($memID, $email = false, $membername = false, $post_count = false)
  1029. {
  1030. global $smcFunc;
  1031. // Firstly, if email and username aren't passed find out the members email address and name.
  1032. if ($email === false && $membername === false)
  1033. {
  1034. $request = $smcFunc['db_query']('', '
  1035. SELECT email_address, member_name
  1036. FROM {db_prefix}members
  1037. WHERE id_member = {int:memID}
  1038. LIMIT 1',
  1039. array(
  1040. 'memID' => $memID,
  1041. )
  1042. );
  1043. list ($email, $membername) = $smcFunc['db_fetch_row']($request);
  1044. $smcFunc['db_free_result']($request);
  1045. }
  1046. // If they want the post count restored then we need to do some research.
  1047. if ($post_count)
  1048. {
  1049. $request = $smcFunc['db_query']('', '
  1050. SELECT COUNT(*)
  1051. FROM {db_prefix}messages AS m
  1052. INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board AND b.count_posts = {int:count_posts})
  1053. WHERE m.id_member = {int:guest_id}
  1054. AND m.approved = {int:is_approved}
  1055. AND m.icon != {string:recycled_icon}' . (empty($email) ? '' : '
  1056. AND m.poster_email = {string:email_address}') . (empty($membername) ? '' : '
  1057. AND m.poster_name = {string:member_name}'),
  1058. array(
  1059. 'count_posts' => 0,
  1060. 'guest_id' => 0,
  1061. 'email_address' => $email,
  1062. 'member_name' => $membername,
  1063. 'is_approved' => 1,
  1064. 'recycled_icon' => 'recycled',
  1065. )
  1066. );
  1067. list ($messageCount) = $smcFunc['db_fetch_row']($request);
  1068. $smcFunc['db_free_result']($request);
  1069. updateMemberData($memID, array('posts' => 'posts + ' . $messageCount));
  1070. }
  1071. $query_parts = array();
  1072. if (!empty($email))
  1073. $query_parts[] = 'poster_email = {string:email_address}';
  1074. if (!empty($membername))
  1075. $query_parts[] = 'poster_name = {string:member_name}';
  1076. $query = implode(' AND ', $query_parts);
  1077. // Finally, update the posts themselves!
  1078. $smcFunc['db_query']('', '
  1079. UPDATE {db_prefix}messages
  1080. SET id_member = {int:memID}
  1081. WHERE ' . $query,
  1082. array(
  1083. 'memID' => $memID,
  1084. 'email_address' => $email,
  1085. 'member_name' => $membername,
  1086. )
  1087. );
  1088. // ...and the topics too!
  1089. $smcFunc['db_query']('', '
  1090. UPDATE {db_prefix}topics as t, {db_prefix}messages as m
  1091. SET t.id_member_started = {int:memID}
  1092. WHERE m.id_member = {int:memID}
  1093. AND t.id_first_msg = m.id_msg',
  1094. array(
  1095. 'memID' => $memID,
  1096. )
  1097. );
  1098. // Allow mods with their own post tables to reattribute posts as well :)
  1099. call_integration_hook('integrate_reattribute_posts', array($memID, $email, $membername, $post_count));
  1100. }
  1101. /**
  1102. * This simple function adds/removes the passed user from the current users buddy list.
  1103. * Requires profile_identity_own permission.
  1104. * Called by ?action=buddy;u=x;session_id=y.
  1105. * Redirects to ?action=profile;u=x.
  1106. */
  1107. function BuddyListToggle()
  1108. {
  1109. global $user_info;
  1110. checkSession('get');
  1111. isAllowedTo('profile_identity_own');
  1112. is_not_guest();
  1113. if (empty($_REQUEST['u']))
  1114. fatal_lang_error('no_access', false);
  1115. $_REQUEST['u'] = (int) $_REQUEST['u'];
  1116. // Remove if it's already there...
  1117. if (in_array($_REQUEST['u'], $user_info['buddies']))
  1118. $user_info['buddies'] = array_diff($user_info['buddies'], array($_REQUEST['u']));
  1119. // ...or add if it's not and if it's not you.
  1120. elseif ($user_info['id'] != $_REQUEST['u'])
  1121. $user_info['buddies'][] = (int) $_REQUEST['u'];
  1122. // Update the settings.
  1123. updateMemberData($user_info['id'], array('buddy_list' => implode(',', $user_info['buddies'])));
  1124. // Redirect back to the profile
  1125. redirectexit('action=profile;u=' . $_REQUEST['u']);
  1126. }
  1127. /**
  1128. * Callback for createList().
  1129. *
  1130. * @param $start
  1131. * @param $items_per_page
  1132. * @param $sort
  1133. * @param $where
  1134. * @param $where_params
  1135. * @param $get_duplicates
  1136. */
  1137. function list_getMembers($start, $items_per_page, $sort, $where, $where_params = array(), $get_duplicates = false)
  1138. {
  1139. global $smcFunc;
  1140. $request = $smcFunc['db_query']('', '
  1141. SELECT
  1142. mem.id_member, mem.member_name, mem.real_name, mem.email_address, mem.icq, mem.aim, mem.yim, mem.skype, mem.member_ip, mem.member_ip2, mem.last_login,
  1143. mem.posts, mem.is_activated, mem.date_registered, mem.id_group, mem.additional_groups, mg.group_name
  1144. FROM {db_prefix}members AS mem
  1145. LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)
  1146. WHERE ' . ($where == '1' ? '1=1' : $where) . '
  1147. ORDER BY {raw:sort}
  1148. LIMIT {int:start}, {int:per_page}',
  1149. array_merge($where_params, array(
  1150. 'sort' => $sort,
  1151. 'start' => $start,
  1152. 'per_page' => $items_per_page,
  1153. ))
  1154. );
  1155. $members = array();
  1156. while ($row = $smcFunc['db_fetch_assoc']($request))
  1157. $members[] = $row;
  1158. $smcFunc['db_free_result']($request);
  1159. // If we want duplicates pass the members array off.
  1160. if ($get_duplicates)
  1161. populateDuplicateMembers($members);
  1162. return $members;
  1163. }
  1164. /**
  1165. * Callback for createList().
  1166. *
  1167. * @param $where
  1168. * @param $where_params
  1169. */
  1170. function list_getNumMembers($where, $where_params = array())
  1171. {
  1172. global $smcFunc, $modSettings;
  1173. // We know how many members there are in total.
  1174. if (empty($where) || $where == '1=1')
  1175. $num_members = $modSettings['totalMembers'];
  1176. // The database knows the amount when there are extra conditions.
  1177. else
  1178. {
  1179. $request = $smcFunc['db_query']('', '
  1180. SELECT COUNT(*)
  1181. FROM {db_prefix}members AS mem
  1182. WHERE ' . $where,
  1183. array_merge($where_params, array(
  1184. ))
  1185. );
  1186. list ($num_members) = $smcFunc['db_fetch_row']($request);
  1187. $smcFunc['db_free_result']($request);
  1188. }
  1189. return $num_members;
  1190. }
  1191. /**
  1192. * Find potential duplicate registation members based on the same IP address
  1193. *
  1194. * @param $members
  1195. */
  1196. function populateDuplicateMembers(&$members)
  1197. {
  1198. global $smcFunc;
  1199. // This will hold all the ip addresses.
  1200. $ips = array();
  1201. foreach ($members as $key => $member)
  1202. {
  1203. // Create the duplicate_members element.
  1204. $members[$key]['duplicate_members'] = array();
  1205. // Store the IPs.
  1206. if (!empty($member['member_ip']))
  1207. $ips[] = $member['member_ip'];
  1208. if (!empty($member['member_ip2']))
  1209. $ips[] = $member['member_ip2'];
  1210. }
  1211. $ips = array_unique($ips);
  1212. if (empty($ips))
  1213. return false;
  1214. // Fetch all members with this IP address, we'll filter out the current ones in a sec.
  1215. $request = $smcFunc['db_query']('', '
  1216. SELECT
  1217. id_member, member_name, email_address, member_ip, member_ip2, is_activated
  1218. FROM {db_prefix}members
  1219. WHERE member_ip IN ({array_string:ips})
  1220. OR member_ip2 IN ({array_string:ips})',
  1221. array(
  1222. 'ips' => $ips,
  1223. )
  1224. );
  1225. $duplicate_members = array();
  1226. $duplicate_ids = array();
  1227. while ($row = $smcFunc['db_fetch_assoc']($request))
  1228. {
  1229. //$duplicate_ids[] = $row['id_member'];
  1230. $member_context = array(
  1231. 'id' => $row['id_member'],
  1232. 'name' => $row['member_name'],
  1233. 'email' => $row['email_address'],
  1234. 'is_banned' => $row['is_activated'] > 10,
  1235. 'ip' => $row['member_ip'],
  1236. 'ip2' => $row['member_ip2'],
  1237. );
  1238. if (in_array($row['member_ip'], $ips))
  1239. $duplicate_members[$row['member_ip']][] = $member_context;
  1240. if ($row['member_ip'] != $row['member_ip2'] && in_array($row['member_ip2'], $ips))
  1241. $duplicate_members[$row['member_ip2']][] = $member_context;
  1242. }
  1243. $smcFunc['db_free_result']($request);
  1244. // Also try to get a list of messages using these ips.
  1245. $request = $smcFunc['db_query']('', '
  1246. SELECT
  1247. m.poster_ip, mem.id_member, mem.member_name, mem.email_address, mem.is_activated
  1248. FROM {db_prefix}messages AS m
  1249. INNER JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
  1250. WHERE m.id_member != 0
  1251. ' . (!empty($duplicate_ids) ? 'AND m.id_member NOT IN ({array_int:duplicate_ids})' : '') . '
  1252. AND m.poster_ip IN ({array_string:ips})',
  1253. array(
  1254. 'duplicate_ids' => $duplicate_ids,
  1255. 'ips' => $ips,
  1256. )
  1257. );
  1258. $had_ips = array();
  1259. while ($row = $smcFunc['db_fetch_assoc']($request))
  1260. {
  1261. // Don't collect lots of the same.
  1262. if (isset($had_ips[$row['poster_ip']]) && in_array($row['id_member'], $had_ips[$row['poster_ip']]))
  1263. continue;
  1264. $had_ips[$row['poster_ip']][] = $row['id_member'];
  1265. $duplicate_members[$row['poster_ip']][] = array(
  1266. 'id' => $row['id_member'],
  1267. 'name' => $row['member_name'],
  1268. 'email' => $row['email_address'],
  1269. 'is_banned' => $row['is_activated'] > 10,
  1270. 'ip' => $row['poster_ip'],
  1271. 'ip2' => $row['poster_ip'],
  1272. );
  1273. }
  1274. $smcFunc['db_free_result']($request);
  1275. // Now we have all the duplicate members, stick them with their respective member in the list.
  1276. if (!empty($duplicate_members))
  1277. foreach ($members as $key => $member)
  1278. {
  1279. if (isset($duplicate_members[$member['member_ip']]))
  1280. $members[$key]['duplicate_members'] = $duplicate_members[$member['member_ip']];
  1281. if ($member['member_ip'] != $member['member_ip2'] && isset($duplicate_members[$member['member_ip2']]))
  1282. $members[$key]['duplicate_members'] = array_merge($member['duplicate_members'], $duplicate_members[$member['member_ip2']]);
  1283. // Check we don't have lots of the same member.
  1284. $member_track = array($member['id_member']);
  1285. foreach ($members[$key]['duplicate_members'] as $duplicate_id_member => $duplicate_member)
  1286. {
  1287. if (in_array($duplicate_member['id'], $member_track))
  1288. {
  1289. unset($members[$key]['duplicate_members'][$duplicate_id_member]);
  1290. continue;
  1291. }
  1292. $member_track[] = $duplicate_member['id'];
  1293. }
  1294. }
  1295. }
  1296. /**
  1297. * Generate a random validation code.
  1298. * @todo Err. Whatcha doin' here.
  1299. *
  1300. * @return type
  1301. */
  1302. function generateValidationCode()
  1303. {
  1304. global $smcFunc, $modSettings;
  1305. $request = $smcFunc['db_query']('get_random_number', '
  1306. SELECT RAND()',
  1307. array(
  1308. )
  1309. );
  1310. list ($dbRand) = $smcFunc['db_fetch_row']($request);
  1311. $smcFunc['db_free_result']($request);
  1312. return substr(preg_replace('/\W/', '', sha1(microtime() . mt_rand() . $dbRand . $modSettings['rand_seed'])), 0, 10);
  1313. }
  1314. ?>