Subs-Members.php 44 KB

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