PageRenderTime 65ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/wwwroot/phpbb/includes/functions_user.php

https://github.com/spring/spring-website
PHP | 3684 lines | 2601 code | 550 blank | 533 comment | 467 complexity | d2359e1a96343c8c47e34b133b055eeb MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0, LGPL-3.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. *
  4. * This file is part of the phpBB Forum Software package.
  5. *
  6. * @copyright (c) phpBB Limited <https://www.phpbb.com>
  7. * @license GNU General Public License, version 2 (GPL-2.0)
  8. *
  9. * For full copyright and license information, please see
  10. * the docs/CREDITS.txt file.
  11. *
  12. */
  13. /**
  14. * @ignore
  15. */
  16. if (!defined('IN_PHPBB'))
  17. {
  18. exit;
  19. }
  20. /**
  21. * Obtain user_ids from usernames or vice versa. Returns false on
  22. * success else the error string
  23. *
  24. * @param array &$user_id_ary The user ids to check or empty if usernames used
  25. * @param array &$username_ary The usernames to check or empty if user ids used
  26. * @param mixed $user_type Array of user types to check, false if not restricting by user type
  27. */
  28. function user_get_id_name(&$user_id_ary, &$username_ary, $user_type = false)
  29. {
  30. global $db;
  31. // Are both arrays already filled? Yep, return else
  32. // are neither array filled?
  33. if ($user_id_ary && $username_ary)
  34. {
  35. return false;
  36. }
  37. else if (!$user_id_ary && !$username_ary)
  38. {
  39. return 'NO_USERS';
  40. }
  41. $which_ary = ($user_id_ary) ? 'user_id_ary' : 'username_ary';
  42. if (${$which_ary} && !is_array(${$which_ary}))
  43. {
  44. ${$which_ary} = array(${$which_ary});
  45. }
  46. $sql_in = ($which_ary == 'user_id_ary') ? array_map('intval', ${$which_ary}) : array_map('utf8_clean_string', ${$which_ary});
  47. unset(${$which_ary});
  48. $user_id_ary = $username_ary = array();
  49. // Grab the user id/username records
  50. $sql_where = ($which_ary == 'user_id_ary') ? 'user_id' : 'username_clean';
  51. $sql = 'SELECT user_id, username
  52. FROM ' . USERS_TABLE . '
  53. WHERE ' . $db->sql_in_set($sql_where, $sql_in);
  54. if ($user_type !== false && !empty($user_type))
  55. {
  56. $sql .= ' AND ' . $db->sql_in_set('user_type', $user_type);
  57. }
  58. $result = $db->sql_query($sql);
  59. if (!($row = $db->sql_fetchrow($result)))
  60. {
  61. $db->sql_freeresult($result);
  62. return 'NO_USERS';
  63. }
  64. do
  65. {
  66. $username_ary[$row['user_id']] = $row['username'];
  67. $user_id_ary[] = $row['user_id'];
  68. }
  69. while ($row = $db->sql_fetchrow($result));
  70. $db->sql_freeresult($result);
  71. return false;
  72. }
  73. /**
  74. * Get latest registered username and update database to reflect it
  75. */
  76. function update_last_username()
  77. {
  78. global $db;
  79. // Get latest username
  80. $sql = 'SELECT user_id, username, user_colour
  81. FROM ' . USERS_TABLE . '
  82. WHERE user_type IN (' . USER_NORMAL . ', ' . USER_FOUNDER . ')
  83. ORDER BY user_id DESC';
  84. $result = $db->sql_query_limit($sql, 1);
  85. $row = $db->sql_fetchrow($result);
  86. $db->sql_freeresult($result);
  87. if ($row)
  88. {
  89. set_config('newest_user_id', $row['user_id'], true);
  90. set_config('newest_username', $row['username'], true);
  91. set_config('newest_user_colour', $row['user_colour'], true);
  92. }
  93. }
  94. /**
  95. * Updates a username across all relevant tables/fields
  96. *
  97. * @param string $old_name the old/current username
  98. * @param string $new_name the new username
  99. */
  100. function user_update_name($old_name, $new_name)
  101. {
  102. global $config, $db, $cache, $phpbb_dispatcher;
  103. $update_ary = array(
  104. FORUMS_TABLE => array('forum_last_poster_name'),
  105. MODERATOR_CACHE_TABLE => array('username'),
  106. POSTS_TABLE => array('post_username'),
  107. TOPICS_TABLE => array('topic_first_poster_name', 'topic_last_poster_name'),
  108. );
  109. foreach ($update_ary as $table => $field_ary)
  110. {
  111. foreach ($field_ary as $field)
  112. {
  113. $sql = "UPDATE $table
  114. SET $field = '" . $db->sql_escape($new_name) . "'
  115. WHERE $field = '" . $db->sql_escape($old_name) . "'";
  116. $db->sql_query($sql);
  117. }
  118. }
  119. if ($config['newest_username'] == $old_name)
  120. {
  121. set_config('newest_username', $new_name, true);
  122. }
  123. /**
  124. * Update a username when it is changed
  125. *
  126. * @event core.update_username
  127. * @var string old_name The old username that is replaced
  128. * @var string new_name The new username
  129. * @since 3.1.0-a1
  130. */
  131. $vars = array('old_name', 'new_name');
  132. extract($phpbb_dispatcher->trigger_event('core.update_username', compact($vars)));
  133. // Because some tables/caches use username-specific data we need to purge this here.
  134. $cache->destroy('sql', MODERATOR_CACHE_TABLE);
  135. }
  136. /**
  137. * Adds an user
  138. *
  139. * @param mixed $user_row An array containing the following keys (and the appropriate values): username, group_id (the group to place the user in), user_email and the user_type(usually 0). Additional entries not overridden by defaults will be forwarded.
  140. * @param string $cp_data custom profile fields, see custom_profile::build_insert_sql_array
  141. * @param array $notifications_data The notifications settings for the new user
  142. * @return the new user's ID.
  143. */
  144. function user_add($user_row, $cp_data = false, $notifications_data = null)
  145. {
  146. global $db, $user, $auth, $config, $phpbb_root_path, $phpEx;
  147. global $phpbb_dispatcher, $phpbb_container;
  148. if (empty($user_row['username']) || !isset($user_row['group_id']) || !isset($user_row['user_email']) || !isset($user_row['user_type']))
  149. {
  150. return false;
  151. }
  152. $username_clean = utf8_clean_string($user_row['username']);
  153. if (empty($username_clean))
  154. {
  155. return false;
  156. }
  157. $sql_ary = array(
  158. 'username' => $user_row['username'],
  159. 'username_clean' => $username_clean,
  160. 'user_password' => (isset($user_row['user_password'])) ? $user_row['user_password'] : '',
  161. 'user_email' => strtolower($user_row['user_email']),
  162. 'user_email_hash' => phpbb_email_hash($user_row['user_email']),
  163. 'group_id' => $user_row['group_id'],
  164. 'user_type' => $user_row['user_type'],
  165. );
  166. // These are the additional vars able to be specified
  167. $additional_vars = array(
  168. 'user_permissions' => '',
  169. 'user_timezone' => $config['board_timezone'],
  170. 'user_dateformat' => $config['default_dateformat'],
  171. 'user_lang' => $config['default_lang'],
  172. 'user_style' => (int) $config['default_style'],
  173. 'user_actkey' => '',
  174. 'user_ip' => '',
  175. 'user_regdate' => time(),
  176. 'user_passchg' => time(),
  177. 'user_options' => 230271,
  178. // We do not set the new flag here - registration scripts need to specify it
  179. 'user_new' => 0,
  180. 'user_inactive_reason' => 0,
  181. 'user_inactive_time' => 0,
  182. 'user_lastmark' => time(),
  183. 'user_lastvisit' => 0,
  184. 'user_lastpost_time' => 0,
  185. 'user_lastpage' => '',
  186. 'user_posts' => 0,
  187. 'user_colour' => '',
  188. 'user_avatar' => '',
  189. 'user_avatar_type' => '',
  190. 'user_avatar_width' => 0,
  191. 'user_avatar_height' => 0,
  192. 'user_new_privmsg' => 0,
  193. 'user_unread_privmsg' => 0,
  194. 'user_last_privmsg' => 0,
  195. 'user_message_rules' => 0,
  196. 'user_full_folder' => PRIVMSGS_NO_BOX,
  197. 'user_emailtime' => 0,
  198. 'user_notify' => 0,
  199. 'user_notify_pm' => 1,
  200. 'user_notify_type' => NOTIFY_EMAIL,
  201. 'user_allow_pm' => 1,
  202. 'user_allow_viewonline' => 1,
  203. 'user_allow_viewemail' => 1,
  204. 'user_allow_massemail' => 1,
  205. 'user_sig' => '',
  206. 'user_sig_bbcode_uid' => '',
  207. 'user_sig_bbcode_bitfield' => '',
  208. 'user_form_salt' => unique_id(),
  209. );
  210. // Now fill the sql array with not required variables
  211. foreach ($additional_vars as $key => $default_value)
  212. {
  213. $sql_ary[$key] = (isset($user_row[$key])) ? $user_row[$key] : $default_value;
  214. }
  215. // Any additional variables in $user_row not covered above?
  216. $remaining_vars = array_diff(array_keys($user_row), array_keys($sql_ary));
  217. // Now fill our sql array with the remaining vars
  218. if (sizeof($remaining_vars))
  219. {
  220. foreach ($remaining_vars as $key)
  221. {
  222. $sql_ary[$key] = $user_row[$key];
  223. }
  224. }
  225. /**
  226. * Use this event to modify the values to be inserted when a user is added
  227. *
  228. * @event core.user_add_modify_data
  229. * @var array user_row Array of user details submited to user_add
  230. * @var array cp_data Array of Custom profile fields submited to user_add
  231. * @var array sql_ary Array of data to be inserted when a user is added
  232. * @since 3.1.0-a1
  233. * @change 3.1.0-b5
  234. */
  235. $vars = array('user_row', 'cp_data', 'sql_ary');
  236. extract($phpbb_dispatcher->trigger_event('core.user_add_modify_data', compact($vars)));
  237. $sql = 'INSERT INTO ' . USERS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
  238. $db->sql_query($sql);
  239. $user_id = $db->sql_nextid();
  240. // Insert Custom Profile Fields
  241. if ($cp_data !== false && sizeof($cp_data))
  242. {
  243. $cp_data['user_id'] = (int) $user_id;
  244. $cp = $phpbb_container->get('profilefields.manager');
  245. $sql = 'INSERT INTO ' . PROFILE_FIELDS_DATA_TABLE . ' ' .
  246. $db->sql_build_array('INSERT', $cp->build_insert_sql_array($cp_data));
  247. $db->sql_query($sql);
  248. }
  249. // Place into appropriate group...
  250. $sql = 'INSERT INTO ' . USER_GROUP_TABLE . ' ' . $db->sql_build_array('INSERT', array(
  251. 'user_id' => (int) $user_id,
  252. 'group_id' => (int) $user_row['group_id'],
  253. 'user_pending' => 0)
  254. );
  255. $db->sql_query($sql);
  256. // Now make it the users default group...
  257. group_set_user_default($user_row['group_id'], array($user_id), false);
  258. // Add to newly registered users group if user_new is 1
  259. if ($config['new_member_post_limit'] && $sql_ary['user_new'])
  260. {
  261. $sql = 'SELECT group_id
  262. FROM ' . GROUPS_TABLE . "
  263. WHERE group_name = 'NEWLY_REGISTERED'
  264. AND group_type = " . GROUP_SPECIAL;
  265. $result = $db->sql_query($sql);
  266. $add_group_id = (int) $db->sql_fetchfield('group_id');
  267. $db->sql_freeresult($result);
  268. if ($add_group_id)
  269. {
  270. global $phpbb_log;
  271. // Because these actions only fill the log unneccessarily we skip the add_log() entry.
  272. $phpbb_log->disable('admin');
  273. // Add user to "newly registered users" group and set to default group if admin specified so.
  274. if ($config['new_member_group_default'])
  275. {
  276. group_user_add($add_group_id, $user_id, false, false, true);
  277. $user_row['group_id'] = $add_group_id;
  278. }
  279. else
  280. {
  281. group_user_add($add_group_id, $user_id);
  282. }
  283. $phpbb_log->enable('admin');
  284. }
  285. }
  286. // set the newest user and adjust the user count if the user is a normal user and no activation mail is sent
  287. if ($user_row['user_type'] == USER_NORMAL || $user_row['user_type'] == USER_FOUNDER)
  288. {
  289. set_config('newest_user_id', $user_id, true);
  290. set_config('newest_username', $user_row['username'], true);
  291. set_config_count('num_users', 1, true);
  292. $sql = 'SELECT group_colour
  293. FROM ' . GROUPS_TABLE . '
  294. WHERE group_id = ' . (int) $user_row['group_id'];
  295. $result = $db->sql_query_limit($sql, 1);
  296. $row = $db->sql_fetchrow($result);
  297. $db->sql_freeresult($result);
  298. set_config('newest_user_colour', $row['group_colour'], true);
  299. }
  300. // Use default notifications settings if notifications_data is not set
  301. if ($notifications_data === null)
  302. {
  303. $notifications_data = array(
  304. array(
  305. 'item_type' => 'notification.type.post',
  306. 'method' => 'notification.method.email',
  307. ),
  308. array(
  309. 'item_type' => 'notification.type.topic',
  310. 'method' => 'notification.method.email',
  311. ),
  312. );
  313. }
  314. // Subscribe user to notifications if necessary
  315. if (!empty($notifications_data))
  316. {
  317. $phpbb_notifications = $phpbb_container->get('notification_manager');
  318. foreach ($notifications_data as $subscription)
  319. {
  320. $phpbb_notifications->add_subscription($subscription['item_type'], 0, $subscription['method'], $user_id);
  321. }
  322. }
  323. /**
  324. * Event that returns user id, user detals and user CPF of newly registared user
  325. *
  326. * @event core.user_add_after
  327. * @var int user_id User id of newly registared user
  328. * @var array user_row Array of user details submited to user_add
  329. * @var array cp_data Array of Custom profile fields submited to user_add
  330. * @since 3.1.0-b5
  331. */
  332. $vars = array('user_id', 'user_row', 'cp_data');
  333. extract($phpbb_dispatcher->trigger_event('core.user_add_after', compact($vars)));
  334. return $user_id;
  335. }
  336. /**
  337. * Remove User
  338. *
  339. * @param string $mode Either 'retain' or 'remove'
  340. * @param mixed $user_ids Either an array of integers or an integer
  341. * @param bool $retain_username
  342. * @return bool
  343. */
  344. function user_delete($mode, $user_ids, $retain_username = true)
  345. {
  346. global $cache, $config, $db, $user, $phpbb_dispatcher, $phpbb_container;
  347. global $phpbb_root_path, $phpEx;
  348. $db->sql_transaction('begin');
  349. $user_rows = array();
  350. if (!is_array($user_ids))
  351. {
  352. $user_ids = array($user_ids);
  353. }
  354. $user_id_sql = $db->sql_in_set('user_id', $user_ids);
  355. $sql = 'SELECT *
  356. FROM ' . USERS_TABLE . '
  357. WHERE ' . $user_id_sql;
  358. $result = $db->sql_query($sql);
  359. while ($row = $db->sql_fetchrow($result))
  360. {
  361. $user_rows[(int) $row['user_id']] = $row;
  362. }
  363. $db->sql_freeresult($result);
  364. if (empty($user_rows))
  365. {
  366. return false;
  367. }
  368. /**
  369. * Event before a user is deleted
  370. *
  371. * @event core.delete_user_before
  372. * @var string mode Mode of deletion (retain/delete posts)
  373. * @var array user_ids IDs of the deleted user
  374. * @var mixed retain_username True if username should be retained
  375. * or false if not
  376. * @since 3.1.0-a1
  377. */
  378. $vars = array('mode', 'user_ids', 'retain_username');
  379. extract($phpbb_dispatcher->trigger_event('core.delete_user_before', compact($vars)));
  380. // Before we begin, we will remove the reports the user issued.
  381. $sql = 'SELECT r.post_id, p.topic_id
  382. FROM ' . REPORTS_TABLE . ' r, ' . POSTS_TABLE . ' p
  383. WHERE ' . $db->sql_in_set('r.user_id', $user_ids) . '
  384. AND p.post_id = r.post_id';
  385. $result = $db->sql_query($sql);
  386. $report_posts = $report_topics = array();
  387. while ($row = $db->sql_fetchrow($result))
  388. {
  389. $report_posts[] = $row['post_id'];
  390. $report_topics[] = $row['topic_id'];
  391. }
  392. $db->sql_freeresult($result);
  393. if (sizeof($report_posts))
  394. {
  395. $report_posts = array_unique($report_posts);
  396. $report_topics = array_unique($report_topics);
  397. // Get a list of topics that still contain reported posts
  398. $sql = 'SELECT DISTINCT topic_id
  399. FROM ' . POSTS_TABLE . '
  400. WHERE ' . $db->sql_in_set('topic_id', $report_topics) . '
  401. AND post_reported = 1
  402. AND ' . $db->sql_in_set('post_id', $report_posts, true);
  403. $result = $db->sql_query($sql);
  404. $keep_report_topics = array();
  405. while ($row = $db->sql_fetchrow($result))
  406. {
  407. $keep_report_topics[] = $row['topic_id'];
  408. }
  409. $db->sql_freeresult($result);
  410. if (sizeof($keep_report_topics))
  411. {
  412. $report_topics = array_diff($report_topics, $keep_report_topics);
  413. }
  414. unset($keep_report_topics);
  415. // Now set the flags back
  416. $sql = 'UPDATE ' . POSTS_TABLE . '
  417. SET post_reported = 0
  418. WHERE ' . $db->sql_in_set('post_id', $report_posts);
  419. $db->sql_query($sql);
  420. if (sizeof($report_topics))
  421. {
  422. $sql = 'UPDATE ' . TOPICS_TABLE . '
  423. SET topic_reported = 0
  424. WHERE ' . $db->sql_in_set('topic_id', $report_topics);
  425. $db->sql_query($sql);
  426. }
  427. }
  428. // Remove reports
  429. $db->sql_query('DELETE FROM ' . REPORTS_TABLE . ' WHERE ' . $user_id_sql);
  430. $num_users_delta = 0;
  431. // Get auth provider collection in case accounts might need to be unlinked
  432. $provider_collection = $phpbb_container->get('auth.provider_collection');
  433. // Some things need to be done in the loop (if the query changes based
  434. // on which user is currently being deleted)
  435. $added_guest_posts = 0;
  436. foreach ($user_rows as $user_id => $user_row)
  437. {
  438. if ($user_row['user_avatar'] && $user_row['user_avatar_type'] == 'avatar.driver.upload')
  439. {
  440. avatar_delete('user', $user_row);
  441. }
  442. // Unlink accounts
  443. foreach ($provider_collection as $provider_name => $auth_provider)
  444. {
  445. $provider_data = $auth_provider->get_auth_link_data($user_id);
  446. if ($provider_data !== null)
  447. {
  448. $link_data = array(
  449. 'user_id' => $user_id,
  450. 'link_method' => 'user_delete',
  451. );
  452. // BLOCK_VARS might contain hidden fields necessary for unlinking accounts
  453. if (isset($provider_data['BLOCK_VARS']) && is_array($provider_data['BLOCK_VARS']))
  454. {
  455. foreach ($provider_data['BLOCK_VARS'] as $provider_service)
  456. {
  457. if (!array_key_exists('HIDDEN_FIELDS', $provider_service))
  458. {
  459. $provider_service['HIDDEN_FIELDS'] = array();
  460. }
  461. $auth_provider->unlink_account(array_merge($link_data, $provider_service['HIDDEN_FIELDS']));
  462. }
  463. }
  464. else
  465. {
  466. $auth_provider->unlink_account($link_data);
  467. }
  468. }
  469. }
  470. // Decrement number of users if this user is active
  471. if ($user_row['user_type'] != USER_INACTIVE && $user_row['user_type'] != USER_IGNORE)
  472. {
  473. --$num_users_delta;
  474. }
  475. switch ($mode)
  476. {
  477. case 'retain':
  478. if ($retain_username === false)
  479. {
  480. $post_username = $user->lang['GUEST'];
  481. }
  482. else
  483. {
  484. $post_username = $user_row['username'];
  485. }
  486. // If the user is inactive and newly registered
  487. // we assume no posts from the user, and save
  488. // the queries
  489. if ($user_row['user_type'] != USER_INACTIVE || $user_row['user_inactive_reason'] != INACTIVE_REGISTER || $user_row['user_posts'])
  490. {
  491. // When we delete these users and retain the posts, we must assign all the data to the guest user
  492. $sql = 'UPDATE ' . FORUMS_TABLE . '
  493. SET forum_last_poster_id = ' . ANONYMOUS . ", forum_last_poster_name = '" . $db->sql_escape($post_username) . "', forum_last_poster_colour = ''
  494. WHERE forum_last_poster_id = $user_id";
  495. $db->sql_query($sql);
  496. $sql = 'UPDATE ' . POSTS_TABLE . '
  497. SET poster_id = ' . ANONYMOUS . ", post_username = '" . $db->sql_escape($post_username) . "'
  498. WHERE poster_id = $user_id";
  499. $db->sql_query($sql);
  500. $sql = 'UPDATE ' . TOPICS_TABLE . '
  501. SET topic_poster = ' . ANONYMOUS . ", topic_first_poster_name = '" . $db->sql_escape($post_username) . "', topic_first_poster_colour = ''
  502. WHERE topic_poster = $user_id";
  503. $db->sql_query($sql);
  504. $sql = 'UPDATE ' . TOPICS_TABLE . '
  505. SET topic_last_poster_id = ' . ANONYMOUS . ", topic_last_poster_name = '" . $db->sql_escape($post_username) . "', topic_last_poster_colour = ''
  506. WHERE topic_last_poster_id = $user_id";
  507. $db->sql_query($sql);
  508. // Since we change every post by this author, we need to count this amount towards the anonymous user
  509. if ($user_row['user_posts'])
  510. {
  511. $added_guest_posts += $user_row['user_posts'];
  512. }
  513. }
  514. break;
  515. case 'remove':
  516. // there is nothing variant specific to deleting posts
  517. break;
  518. }
  519. }
  520. if ($num_users_delta != 0)
  521. {
  522. set_config_count('num_users', $num_users_delta, true);
  523. }
  524. // Now do the invariant tasks
  525. // all queries performed in one call of this function are in a single transaction
  526. // so this is kosher
  527. if ($mode == 'retain')
  528. {
  529. // Assign more data to the Anonymous user
  530. $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
  531. SET poster_id = ' . ANONYMOUS . '
  532. WHERE ' . $db->sql_in_set('poster_id', $user_ids);
  533. $db->sql_query($sql);
  534. $sql = 'UPDATE ' . USERS_TABLE . '
  535. SET user_posts = user_posts + ' . $added_guest_posts . '
  536. WHERE user_id = ' . ANONYMOUS;
  537. $db->sql_query($sql);
  538. }
  539. else if ($mode == 'remove')
  540. {
  541. if (!function_exists('delete_posts'))
  542. {
  543. include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
  544. }
  545. // Delete posts, attachments, etc.
  546. // delete_posts can handle any number of IDs in its second argument
  547. delete_posts('poster_id', $user_ids);
  548. }
  549. $table_ary = array(USERS_TABLE, USER_GROUP_TABLE, TOPICS_WATCH_TABLE, FORUMS_WATCH_TABLE, ACL_USERS_TABLE, TOPICS_TRACK_TABLE, TOPICS_POSTED_TABLE, FORUMS_TRACK_TABLE, PROFILE_FIELDS_DATA_TABLE, MODERATOR_CACHE_TABLE, DRAFTS_TABLE, BOOKMARKS_TABLE, SESSIONS_KEYS_TABLE, PRIVMSGS_FOLDER_TABLE, PRIVMSGS_RULES_TABLE);
  550. // Delete the miscellaneous (non-post) data for the user
  551. foreach ($table_ary as $table)
  552. {
  553. $sql = "DELETE FROM $table
  554. WHERE " . $user_id_sql;
  555. $db->sql_query($sql);
  556. }
  557. $cache->destroy('sql', MODERATOR_CACHE_TABLE);
  558. // Change user_id to anonymous for posts edited by this user
  559. $sql = 'UPDATE ' . POSTS_TABLE . '
  560. SET post_edit_user = ' . ANONYMOUS . '
  561. WHERE ' . $db->sql_in_set('post_edit_user', $user_ids);
  562. $db->sql_query($sql);
  563. // Change user_id to anonymous for pms edited by this user
  564. $sql = 'UPDATE ' . PRIVMSGS_TABLE . '
  565. SET message_edit_user = ' . ANONYMOUS . '
  566. WHERE ' . $db->sql_in_set('message_edit_user', $user_ids);
  567. $db->sql_query($sql);
  568. // Change user_id to anonymous for posts deleted by this user
  569. $sql = 'UPDATE ' . POSTS_TABLE . '
  570. SET post_delete_user = ' . ANONYMOUS . '
  571. WHERE ' . $db->sql_in_set('post_delete_user', $user_ids);
  572. $db->sql_query($sql);
  573. // Change user_id to anonymous for topics deleted by this user
  574. $sql = 'UPDATE ' . TOPICS_TABLE . '
  575. SET topic_delete_user = ' . ANONYMOUS . '
  576. WHERE ' . $db->sql_in_set('topic_delete_user', $user_ids);
  577. $db->sql_query($sql);
  578. // Delete user log entries about this user
  579. $sql = 'DELETE FROM ' . LOG_TABLE . '
  580. WHERE ' . $db->sql_in_set('reportee_id', $user_ids);
  581. $db->sql_query($sql);
  582. // Change user_id to anonymous for this users triggered events
  583. $sql = 'UPDATE ' . LOG_TABLE . '
  584. SET user_id = ' . ANONYMOUS . '
  585. WHERE ' . $user_id_sql;
  586. $db->sql_query($sql);
  587. // Delete the user_id from the zebra table
  588. $sql = 'DELETE FROM ' . ZEBRA_TABLE . '
  589. WHERE ' . $user_id_sql . '
  590. OR ' . $db->sql_in_set('zebra_id', $user_ids);
  591. $db->sql_query($sql);
  592. // Delete the user_id from the banlist
  593. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  594. WHERE ' . $db->sql_in_set('ban_userid', $user_ids);
  595. $db->sql_query($sql);
  596. // Delete the user_id from the session table
  597. $sql = 'DELETE FROM ' . SESSIONS_TABLE . '
  598. WHERE ' . $db->sql_in_set('session_user_id', $user_ids);
  599. $db->sql_query($sql);
  600. // Clean the private messages tables from the user
  601. if (!function_exists('phpbb_delete_user_pms'))
  602. {
  603. include($phpbb_root_path . 'includes/functions_privmsgs.' . $phpEx);
  604. }
  605. phpbb_delete_users_pms($user_ids);
  606. $phpbb_notifications = $phpbb_container->get('notification_manager');
  607. $phpbb_notifications->delete_notifications('notification.type.admin_activate_user', $user_ids);
  608. $db->sql_transaction('commit');
  609. /**
  610. * Event after a user is deleted
  611. *
  612. * @event core.delete_user_after
  613. * @var string mode Mode of deletion (retain/delete posts)
  614. * @var array user_ids IDs of the deleted user
  615. * @var mixed retain_username True if username should be retained
  616. * or false if not
  617. * @since 3.1.0-a1
  618. */
  619. $vars = array('mode', 'user_ids', 'retain_username');
  620. extract($phpbb_dispatcher->trigger_event('core.delete_user_after', compact($vars)));
  621. // Reset newest user info if appropriate
  622. if (in_array($config['newest_user_id'], $user_ids))
  623. {
  624. update_last_username();
  625. }
  626. return false;
  627. }
  628. /**
  629. * Flips user_type from active to inactive and vice versa, handles group membership updates
  630. *
  631. * @param string $mode can be flip for flipping from active/inactive, activate or deactivate
  632. */
  633. function user_active_flip($mode, $user_id_ary, $reason = INACTIVE_MANUAL)
  634. {
  635. global $config, $db, $user, $auth, $phpbb_dispatcher;
  636. $deactivated = $activated = 0;
  637. $sql_statements = array();
  638. if (!is_array($user_id_ary))
  639. {
  640. $user_id_ary = array($user_id_ary);
  641. }
  642. if (!sizeof($user_id_ary))
  643. {
  644. return;
  645. }
  646. $sql = 'SELECT user_id, group_id, user_type, user_inactive_reason
  647. FROM ' . USERS_TABLE . '
  648. WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
  649. $result = $db->sql_query($sql);
  650. while ($row = $db->sql_fetchrow($result))
  651. {
  652. $sql_ary = array();
  653. if ($row['user_type'] == USER_IGNORE || $row['user_type'] == USER_FOUNDER ||
  654. ($mode == 'activate' && $row['user_type'] != USER_INACTIVE) ||
  655. ($mode == 'deactivate' && $row['user_type'] == USER_INACTIVE))
  656. {
  657. continue;
  658. }
  659. if ($row['user_type'] == USER_INACTIVE)
  660. {
  661. $activated++;
  662. }
  663. else
  664. {
  665. $deactivated++;
  666. // Remove the users session key...
  667. $user->reset_login_keys($row['user_id']);
  668. }
  669. $sql_ary += array(
  670. 'user_type' => ($row['user_type'] == USER_NORMAL) ? USER_INACTIVE : USER_NORMAL,
  671. 'user_inactive_time' => ($row['user_type'] == USER_NORMAL) ? time() : 0,
  672. 'user_inactive_reason' => ($row['user_type'] == USER_NORMAL) ? $reason : 0,
  673. );
  674. $sql_statements[$row['user_id']] = $sql_ary;
  675. }
  676. $db->sql_freeresult($result);
  677. /**
  678. * Check or modify activated/deactivated users data before submitting it to the database
  679. *
  680. * @event core.user_active_flip_before
  681. * @var string mode User type changing mode, can be: flip|activate|deactivate
  682. * @var int reason Reason for changing user type, can be: INACTIVE_REGISTER|INACTIVE_PROFILE|INACTIVE_MANUAL|INACTIVE_REMIND
  683. * @var int activated The number of users to be activated
  684. * @var int deactivated The number of users to be deactivated
  685. * @var array user_id_ary Array with user ids to change user type
  686. * @var array sql_statements Array with users data to submit to the database, keys: user ids, values: arrays with user data
  687. * @since 3.1.4-RC1
  688. */
  689. $vars = array('mode', 'reason', 'activated', 'deactivated', 'user_id_ary', 'sql_statements');
  690. extract($phpbb_dispatcher->trigger_event('core.user_active_flip_before', compact($vars)));
  691. if (sizeof($sql_statements))
  692. {
  693. foreach ($sql_statements as $user_id => $sql_ary)
  694. {
  695. $sql = 'UPDATE ' . USERS_TABLE . '
  696. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  697. WHERE user_id = ' . $user_id;
  698. $db->sql_query($sql);
  699. }
  700. $auth->acl_clear_prefetch(array_keys($sql_statements));
  701. }
  702. /**
  703. * Perform additional actions after the users have been activated/deactivated
  704. *
  705. * @event core.user_active_flip_after
  706. * @var string mode User type changing mode, can be: flip|activate|deactivate
  707. * @var int reason Reason for changing user type, can be: INACTIVE_REGISTER|INACTIVE_PROFILE|INACTIVE_MANUAL|INACTIVE_REMIND
  708. * @var int activated The number of users to be activated
  709. * @var int deactivated The number of users to be deactivated
  710. * @var array user_id_ary Array with user ids to change user type
  711. * @var array sql_statements Array with users data to submit to the database, keys: user ids, values: arrays with user data
  712. * @since 3.1.4-RC1
  713. */
  714. $vars = array('mode', 'reason', 'activated', 'deactivated', 'user_id_ary', 'sql_statements');
  715. extract($phpbb_dispatcher->trigger_event('core.user_active_flip_after', compact($vars)));
  716. if ($deactivated)
  717. {
  718. set_config_count('num_users', $deactivated * (-1), true);
  719. }
  720. if ($activated)
  721. {
  722. set_config_count('num_users', $activated, true);
  723. }
  724. // Update latest username
  725. update_last_username();
  726. }
  727. /**
  728. * Add a ban or ban exclusion to the banlist. Bans either a user, an IP or an email address
  729. *
  730. * @param string $mode Type of ban. One of the following: user, ip, email
  731. * @param mixed $ban Banned entity. Either string or array with usernames, ips or email addresses
  732. * @param int $ban_len Ban length in minutes
  733. * @param string $ban_len_other Ban length as a date (YYYY-MM-DD)
  734. * @param boolean $ban_exclude Exclude these entities from banning?
  735. * @param string $ban_reason String describing the reason for this ban
  736. * @return boolean
  737. */
  738. function user_ban($mode, $ban, $ban_len, $ban_len_other, $ban_exclude, $ban_reason, $ban_give_reason = '')
  739. {
  740. global $db, $user, $auth, $cache;
  741. // Delete stale bans
  742. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  743. WHERE ban_end < ' . time() . '
  744. AND ban_end <> 0';
  745. $db->sql_query($sql);
  746. $ban_list = (!is_array($ban)) ? array_unique(explode("\n", $ban)) : $ban;
  747. $ban_list_log = implode(', ', $ban_list);
  748. $current_time = time();
  749. // Set $ban_end to the unix time when the ban should end. 0 is a permanent ban.
  750. if ($ban_len)
  751. {
  752. if ($ban_len != -1 || !$ban_len_other)
  753. {
  754. $ban_end = max($current_time, $current_time + ($ban_len) * 60);
  755. }
  756. else
  757. {
  758. $ban_other = explode('-', $ban_len_other);
  759. if (sizeof($ban_other) == 3 && ((int) $ban_other[0] < 9999) &&
  760. (strlen($ban_other[0]) == 4) && (strlen($ban_other[1]) == 2) && (strlen($ban_other[2]) == 2))
  761. {
  762. $ban_end = max($current_time, $user->create_datetime()
  763. ->setDate((int) $ban_other[0], (int) $ban_other[1], (int) $ban_other[2])
  764. ->setTime(0, 0, 0)
  765. ->getTimestamp() + $user->timezone->getOffset(new DateTime('UTC')));
  766. }
  767. else
  768. {
  769. trigger_error('LENGTH_BAN_INVALID', E_USER_WARNING);
  770. }
  771. }
  772. }
  773. else
  774. {
  775. $ban_end = 0;
  776. }
  777. $founder = $founder_names = array();
  778. if (!$ban_exclude)
  779. {
  780. // Create a list of founder...
  781. $sql = 'SELECT user_id, user_email, username_clean
  782. FROM ' . USERS_TABLE . '
  783. WHERE user_type = ' . USER_FOUNDER;
  784. $result = $db->sql_query($sql);
  785. while ($row = $db->sql_fetchrow($result))
  786. {
  787. $founder[$row['user_id']] = $row['user_email'];
  788. $founder_names[$row['user_id']] = $row['username_clean'];
  789. }
  790. $db->sql_freeresult($result);
  791. }
  792. $banlist_ary = array();
  793. switch ($mode)
  794. {
  795. case 'user':
  796. $type = 'ban_userid';
  797. // At the moment we do not support wildcard username banning
  798. // Select the relevant user_ids.
  799. $sql_usernames = array();
  800. foreach ($ban_list as $username)
  801. {
  802. $username = trim($username);
  803. if ($username != '')
  804. {
  805. $clean_name = utf8_clean_string($username);
  806. if ($clean_name == $user->data['username_clean'])
  807. {
  808. trigger_error('CANNOT_BAN_YOURSELF', E_USER_WARNING);
  809. }
  810. if (in_array($clean_name, $founder_names))
  811. {
  812. trigger_error('CANNOT_BAN_FOUNDER', E_USER_WARNING);
  813. }
  814. $sql_usernames[] = $clean_name;
  815. }
  816. }
  817. // Make sure we have been given someone to ban
  818. if (!sizeof($sql_usernames))
  819. {
  820. trigger_error('NO_USER_SPECIFIED', E_USER_WARNING);
  821. }
  822. $sql = 'SELECT user_id
  823. FROM ' . USERS_TABLE . '
  824. WHERE ' . $db->sql_in_set('username_clean', $sql_usernames);
  825. // Do not allow banning yourself, the guest account, or founders.
  826. $non_bannable = array($user->data['user_id'], ANONYMOUS);
  827. if (sizeof($founder))
  828. {
  829. $sql .= ' AND ' . $db->sql_in_set('user_id', array_merge(array_keys($founder), $non_bannable), true);
  830. }
  831. else
  832. {
  833. $sql .= ' AND ' . $db->sql_in_set('user_id', $non_bannable, true);
  834. }
  835. $result = $db->sql_query($sql);
  836. if ($row = $db->sql_fetchrow($result))
  837. {
  838. do
  839. {
  840. $banlist_ary[] = (int) $row['user_id'];
  841. }
  842. while ($row = $db->sql_fetchrow($result));
  843. }
  844. else
  845. {
  846. $db->sql_freeresult($result);
  847. trigger_error('NO_USERS', E_USER_WARNING);
  848. }
  849. $db->sql_freeresult($result);
  850. break;
  851. case 'ip':
  852. $type = 'ban_ip';
  853. foreach ($ban_list as $ban_item)
  854. {
  855. if (preg_match('#^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})[ ]*\-[ ]*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$#', trim($ban_item), $ip_range_explode))
  856. {
  857. // This is an IP range
  858. // Don't ask about all this, just don't ask ... !
  859. $ip_1_counter = $ip_range_explode[1];
  860. $ip_1_end = $ip_range_explode[5];
  861. while ($ip_1_counter <= $ip_1_end)
  862. {
  863. $ip_2_counter = ($ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[2] : 0;
  864. $ip_2_end = ($ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[6];
  865. if ($ip_2_counter == 0 && $ip_2_end == 254)
  866. {
  867. $ip_2_counter = 256;
  868. $ip_2_fragment = 256;
  869. $banlist_ary[] = "$ip_1_counter.*";
  870. }
  871. while ($ip_2_counter <= $ip_2_end)
  872. {
  873. $ip_3_counter = ($ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[3] : 0;
  874. $ip_3_end = ($ip_2_counter < $ip_2_end || $ip_1_counter < $ip_1_end) ? 254 : $ip_range_explode[7];
  875. if ($ip_3_counter == 0 && $ip_3_end == 254)
  876. {
  877. $ip_3_counter = 256;
  878. $ip_3_fragment = 256;
  879. $banlist_ary[] = "$ip_1_counter.$ip_2_counter.*";
  880. }
  881. while ($ip_3_counter <= $ip_3_end)
  882. {
  883. $ip_4_counter = ($ip_3_counter == $ip_range_explode[3] && $ip_2_counter == $ip_range_explode[2] && $ip_1_counter == $ip_range_explode[1]) ? $ip_range_explode[4] : 0;
  884. $ip_4_end = ($ip_3_counter < $ip_3_end || $ip_2_counter < $ip_2_end) ? 254 : $ip_range_explode[8];
  885. if ($ip_4_counter == 0 && $ip_4_end == 254)
  886. {
  887. $ip_4_counter = 256;
  888. $ip_4_fragment = 256;
  889. $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.*";
  890. }
  891. while ($ip_4_counter <= $ip_4_end)
  892. {
  893. $banlist_ary[] = "$ip_1_counter.$ip_2_counter.$ip_3_counter.$ip_4_counter";
  894. $ip_4_counter++;
  895. }
  896. $ip_3_counter++;
  897. }
  898. $ip_2_counter++;
  899. }
  900. $ip_1_counter++;
  901. }
  902. }
  903. else if (preg_match('#^([0-9]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})\.([0-9\*]{1,3})$#', trim($ban_item)) || preg_match('#^[a-f0-9:]+\*?$#i', trim($ban_item)))
  904. {
  905. // Normal IP address
  906. $banlist_ary[] = trim($ban_item);
  907. }
  908. else if (preg_match('#^\*$#', trim($ban_item)))
  909. {
  910. // Ban all IPs
  911. $banlist_ary[] = '*';
  912. }
  913. else if (preg_match('#^([\w\-_]\.?){2,}$#is', trim($ban_item)))
  914. {
  915. // hostname
  916. $ip_ary = gethostbynamel(trim($ban_item));
  917. if (!empty($ip_ary))
  918. {
  919. foreach ($ip_ary as $ip)
  920. {
  921. if ($ip)
  922. {
  923. if (strlen($ip) > 40)
  924. {
  925. continue;
  926. }
  927. $banlist_ary[] = $ip;
  928. }
  929. }
  930. }
  931. }
  932. if (empty($banlist_ary))
  933. {
  934. trigger_error('NO_IPS_DEFINED', E_USER_WARNING);
  935. }
  936. }
  937. break;
  938. case 'email':
  939. $type = 'ban_email';
  940. foreach ($ban_list as $ban_item)
  941. {
  942. $ban_item = trim($ban_item);
  943. if (preg_match('#^.*?@*|(([a-z0-9\-]+\.)+([a-z]{2,3}))$#i', $ban_item))
  944. {
  945. if (strlen($ban_item) > 100)
  946. {
  947. continue;
  948. }
  949. if (!sizeof($founder) || !in_array($ban_item, $founder))
  950. {
  951. $banlist_ary[] = $ban_item;
  952. }
  953. }
  954. }
  955. if (sizeof($ban_list) == 0)
  956. {
  957. trigger_error('NO_EMAILS_DEFINED', E_USER_WARNING);
  958. }
  959. break;
  960. default:
  961. trigger_error('NO_MODE', E_USER_WARNING);
  962. break;
  963. }
  964. // Fetch currently set bans of the specified type and exclude state. Prevent duplicate bans.
  965. $sql_where = ($type == 'ban_userid') ? 'ban_userid <> 0' : "$type <> ''";
  966. $sql = "SELECT $type
  967. FROM " . BANLIST_TABLE . "
  968. WHERE $sql_where
  969. AND ban_exclude = " . (int) $ban_exclude;
  970. $result = $db->sql_query($sql);
  971. // Reset $sql_where, because we use it later...
  972. $sql_where = '';
  973. if ($row = $db->sql_fetchrow($result))
  974. {
  975. $banlist_ary_tmp = array();
  976. do
  977. {
  978. switch ($mode)
  979. {
  980. case 'user':
  981. $banlist_ary_tmp[] = $row['ban_userid'];
  982. break;
  983. case 'ip':
  984. $banlist_ary_tmp[] = $row['ban_ip'];
  985. break;
  986. case 'email':
  987. $banlist_ary_tmp[] = $row['ban_email'];
  988. break;
  989. }
  990. }
  991. while ($row = $db->sql_fetchrow($result));
  992. $banlist_ary_tmp = array_intersect($banlist_ary, $banlist_ary_tmp);
  993. if (sizeof($banlist_ary_tmp))
  994. {
  995. // One or more entities are already banned/excluded, delete the existing bans, so they can be re-inserted with the given new length
  996. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  997. WHERE ' . $db->sql_in_set($type, $banlist_ary_tmp) . '
  998. AND ban_exclude = ' . (int) $ban_exclude;
  999. $db->sql_query($sql);
  1000. }
  1001. unset($banlist_ary_tmp);
  1002. }
  1003. $db->sql_freeresult($result);
  1004. // We have some entities to ban
  1005. if (sizeof($banlist_ary))
  1006. {
  1007. $sql_ary = array();
  1008. foreach ($banlist_ary as $ban_entry)
  1009. {
  1010. $sql_ary[] = array(
  1011. $type => $ban_entry,
  1012. 'ban_start' => (int) $current_time,
  1013. 'ban_end' => (int) $ban_end,
  1014. 'ban_exclude' => (int) $ban_exclude,
  1015. 'ban_reason' => (string) $ban_reason,
  1016. 'ban_give_reason' => (string) $ban_give_reason,
  1017. );
  1018. }
  1019. $db->sql_multi_insert(BANLIST_TABLE, $sql_ary);
  1020. // If we are banning we want to logout anyone matching the ban
  1021. if (!$ban_exclude)
  1022. {
  1023. switch ($mode)
  1024. {
  1025. case 'user':
  1026. $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $banlist_ary);
  1027. break;
  1028. case 'ip':
  1029. $sql_where = 'WHERE ' . $db->sql_in_set('session_ip', $banlist_ary);
  1030. break;
  1031. case 'email':
  1032. $banlist_ary_sql = array();
  1033. foreach ($banlist_ary as $ban_entry)
  1034. {
  1035. $banlist_ary_sql[] = (string) str_replace('*', '%', $ban_entry);
  1036. }
  1037. $sql = 'SELECT user_id
  1038. FROM ' . USERS_TABLE . '
  1039. WHERE ' . $db->sql_in_set('user_email', $banlist_ary_sql);
  1040. $result = $db->sql_query($sql);
  1041. $sql_in = array();
  1042. if ($row = $db->sql_fetchrow($result))
  1043. {
  1044. do
  1045. {
  1046. $sql_in[] = $row['user_id'];
  1047. }
  1048. while ($row = $db->sql_fetchrow($result));
  1049. $sql_where = 'WHERE ' . $db->sql_in_set('session_user_id', $sql_in);
  1050. }
  1051. $db->sql_freeresult($result);
  1052. break;
  1053. }
  1054. if (isset($sql_where) && $sql_where)
  1055. {
  1056. $sql = 'DELETE FROM ' . SESSIONS_TABLE . "
  1057. $sql_where";
  1058. $db->sql_query($sql);
  1059. if ($mode == 'user')
  1060. {
  1061. $sql = 'DELETE FROM ' . SESSIONS_KEYS_TABLE . ' ' . ((in_array('*', $banlist_ary)) ? '' : 'WHERE ' . $db->sql_in_set('user_id', $banlist_ary));
  1062. $db->sql_query($sql);
  1063. }
  1064. }
  1065. }
  1066. // Update log
  1067. $log_entry = ($ban_exclude) ? 'LOG_BAN_EXCLUDE_' : 'LOG_BAN_';
  1068. // Add to admin log, moderator log and user notes
  1069. add_log('admin', $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
  1070. add_log('mod', 0, 0, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
  1071. if ($mode == 'user')
  1072. {
  1073. foreach ($banlist_ary as $user_id)
  1074. {
  1075. add_log('user', $user_id, $log_entry . strtoupper($mode), $ban_reason, $ban_list_log);
  1076. }
  1077. }
  1078. $cache->destroy('sql', BANLIST_TABLE);
  1079. return true;
  1080. }
  1081. // There was nothing to ban/exclude. But destroying the cache because of the removal of stale bans.
  1082. $cache->destroy('sql', BANLIST_TABLE);
  1083. return false;
  1084. }
  1085. /**
  1086. * Unban User
  1087. */
  1088. function user_unban($mode, $ban)
  1089. {
  1090. global $db, $user, $auth, $cache;
  1091. // Delete stale bans
  1092. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  1093. WHERE ban_end < ' . time() . '
  1094. AND ban_end <> 0';
  1095. $db->sql_query($sql);
  1096. if (!is_array($ban))
  1097. {
  1098. $ban = array($ban);
  1099. }
  1100. $unban_sql = array_map('intval', $ban);
  1101. if (sizeof($unban_sql))
  1102. {
  1103. // Grab details of bans for logging information later
  1104. switch ($mode)
  1105. {
  1106. case 'user':
  1107. $sql = 'SELECT u.username AS unban_info, u.user_id
  1108. FROM ' . USERS_TABLE . ' u, ' . BANLIST_TABLE . ' b
  1109. WHERE ' . $db->sql_in_set('b.ban_id', $unban_sql) . '
  1110. AND u.user_id = b.ban_userid';
  1111. break;
  1112. case 'email':
  1113. $sql = 'SELECT ban_email AS unban_info
  1114. FROM ' . BANLIST_TABLE . '
  1115. WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
  1116. break;
  1117. case 'ip':
  1118. $sql = 'SELECT ban_ip AS unban_info
  1119. FROM ' . BANLIST_TABLE . '
  1120. WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
  1121. break;
  1122. }
  1123. $result = $db->sql_query($sql);
  1124. $l_unban_list = '';
  1125. $user_ids_ary = array();
  1126. while ($row = $db->sql_fetchrow($result))
  1127. {
  1128. $l_unban_list .= (($l_unban_list != '') ? ', ' : '') . $row['unban_info'];
  1129. if ($mode == 'user')
  1130. {
  1131. $user_ids_ary[] = $row['user_id'];
  1132. }
  1133. }
  1134. $db->sql_freeresult($result);
  1135. $sql = 'DELETE FROM ' . BANLIST_TABLE . '
  1136. WHERE ' . $db->sql_in_set('ban_id', $unban_sql);
  1137. $db->sql_query($sql);
  1138. // Add to moderator log, admin log and user notes
  1139. add_log('admin', 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
  1140. add_log('mod', 0, 0, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
  1141. if ($mode == 'user')
  1142. {
  1143. foreach ($user_ids_ary as $user_id)
  1144. {
  1145. add_log('user', $user_id, 'LOG_UNBAN_' . strtoupper($mode), $l_unban_list);
  1146. }
  1147. }
  1148. }
  1149. $cache->destroy('sql', BANLIST_TABLE);
  1150. return false;
  1151. }
  1152. /**
  1153. * Internet Protocol Address Whois
  1154. * RFC3912: WHOIS Protocol Specification
  1155. *
  1156. * @param string $ip Ip address, either IPv4 or IPv6.
  1157. *
  1158. * @return string Empty string if not a valid ip address.
  1159. * Otherwise make_clickable()'ed whois result.
  1160. */
  1161. function user_ipwhois($ip)
  1162. {
  1163. if (empty($ip))
  1164. {
  1165. return '';
  1166. }
  1167. if (preg_match(get_preg_expression('ipv4'), $ip))
  1168. {
  1169. // IPv4 address
  1170. $whois_host = 'whois.arin.net.';
  1171. }
  1172. else if (preg_match(get_preg_expression('ipv6'), $ip))
  1173. {
  1174. // IPv6 address
  1175. $whois_host = 'whois.sixxs.net.';
  1176. }
  1177. else
  1178. {
  1179. return '';
  1180. }
  1181. $ipwhois = '';
  1182. if (($fsk = @fsockopen($whois_host, 43)))
  1183. {
  1184. // CRLF as per RFC3912
  1185. fputs($fsk, "$ip\r\n");
  1186. while (!feof($fsk))
  1187. {
  1188. $ipwhois .= fgets($fsk, 1024);
  1189. }
  1190. @fclose($fsk);
  1191. }
  1192. $match = array();
  1193. // Test for referrals from $whois_host to other whois databases, roll on rwhois
  1194. if (preg_match('#ReferralServer: whois://(.+)#im', $ipwhois, $match))
  1195. {
  1196. if (strpos($match[1], ':') !== false)
  1197. {
  1198. $pos = strrpos($match[1], ':');
  1199. $server = substr($match[1], 0, $pos);
  1200. $port = (int) substr($match[1], $pos + 1);
  1201. unset($pos);
  1202. }
  1203. else
  1204. {
  1205. $server = $match[1];
  1206. $port = 43;
  1207. }
  1208. $buffer = '';
  1209. if (($fsk = @fsockopen($server, $port)))
  1210. {
  1211. fputs($fsk, "$ip\r\n");
  1212. while (!feof($fsk))
  1213. {
  1214. $buffer .= fgets($fsk, 1024);
  1215. }
  1216. @fclose($fsk);
  1217. }
  1218. // Use the result from $whois_host if we don't get any result here
  1219. $ipwhois = (empty($buffer)) ? $ipwhois : $buffer;
  1220. }
  1221. $ipwhois = htmlspecialchars($ipwhois);
  1222. // Magic URL ;)
  1223. return trim(make_clickable($ipwhois, false, ''));
  1224. }
  1225. /**
  1226. * Data validation ... used primarily but not exclusively by ucp modules
  1227. *
  1228. * "Master" function for validating a range of data types
  1229. */
  1230. function validate_data($data, $val_ary)
  1231. {
  1232. global $user;
  1233. $error = array();
  1234. foreach ($val_ary as $var => $val_seq)
  1235. {
  1236. if (!is_array($val_seq[0]))
  1237. {
  1238. $val_seq = array($val_seq);
  1239. }
  1240. foreach ($val_seq as $validate)
  1241. {
  1242. $function = array_shift($validate);
  1243. array_unshift($validate, $data[$var]);
  1244. if (is_array($function))
  1245. {
  1246. $result = call_user_func_array(array($function[0], 'validate_' . $function[1]), $validate);
  1247. }
  1248. else
  1249. {
  1250. $function_prefix = (function_exists('phpbb_validate_' . $function)) ? 'phpbb_validate_' : 'validate_';
  1251. $result = call_user_func_array($function_prefix . $function, $validate);
  1252. }
  1253. if ($result)
  1254. {
  1255. // Since errors are checked later for their language file existence, we need to make sure custom errors are not adjusted.
  1256. $error[] = (empty($user->lang[$result . '_' . strtoupper($var)])) ? $result : $result . '_' . strtoupper($var);
  1257. }
  1258. }
  1259. }
  1260. return $error;
  1261. }
  1262. /**
  1263. * Validate String
  1264. *
  1265. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1266. */
  1267. function validate_string($string, $optional = false, $min = 0, $max = 0)
  1268. {
  1269. if (empty($string) && $optional)
  1270. {
  1271. return false;
  1272. }
  1273. if ($min && utf8_strlen(htmlspecialchars_decode($string)) < $min)
  1274. {
  1275. return 'TOO_SHORT';
  1276. }
  1277. else if ($max && utf8_strlen(htmlspecialchars_decode($string)) > $max)
  1278. {
  1279. return 'TOO_LONG';
  1280. }
  1281. return false;
  1282. }
  1283. /**
  1284. * Validate Number
  1285. *
  1286. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1287. */
  1288. function validate_num($num, $optional = false, $min = 0, $max = 1E99)
  1289. {
  1290. if (empty($num) && $optional)
  1291. {
  1292. return false;
  1293. }
  1294. if ($num < $min)
  1295. {
  1296. return 'TOO_SMALL';
  1297. }
  1298. else if ($num > $max)
  1299. {
  1300. return 'TOO_LARGE';
  1301. }
  1302. return false;
  1303. }
  1304. /**
  1305. * Validate Date
  1306. * @param String $string a date in the dd-mm-yyyy format
  1307. * @return boolean
  1308. */
  1309. function validate_date($date_string, $optional = false)
  1310. {
  1311. $date = explode('-', $date_string);
  1312. if ((empty($date) || sizeof($date) != 3) && $optional)
  1313. {
  1314. return false;
  1315. }
  1316. else if ($optional)
  1317. {
  1318. for ($field = 0; $field <= 1; $field++)
  1319. {
  1320. $date[$field] = (int) $date[$field];
  1321. if (empty($date[$field]))
  1322. {
  1323. $date[$field] = 1;
  1324. }
  1325. }
  1326. $date[2] = (int) $date[2];
  1327. // assume an arbitrary leap year
  1328. if (empty($date[2]))
  1329. {
  1330. $date[2] = 1980;
  1331. }
  1332. }
  1333. if (sizeof($date) != 3 || !checkdate($date[1], $date[0], $date[2]))
  1334. {
  1335. return 'INVALID';
  1336. }
  1337. return false;
  1338. }
  1339. /**
  1340. * Validate Match
  1341. *
  1342. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1343. */
  1344. function validate_match($string, $optional = false, $match = '')
  1345. {
  1346. if (empty($string) && $optional)
  1347. {
  1348. return false;
  1349. }
  1350. if (empty($match))
  1351. {
  1352. return false;
  1353. }
  1354. if (!preg_match($match, $string))
  1355. {
  1356. return 'WRONG_DATA';
  1357. }
  1358. return false;
  1359. }
  1360. /**
  1361. * Validate Language Pack ISO Name
  1362. *
  1363. * Tests whether a language name is valid and installed
  1364. *
  1365. * @param string $lang_iso The language string to test
  1366. *
  1367. * @return bool|string Either false if validation succeeded or
  1368. * a string which will be used as the error message
  1369. * (with the variable name appended)
  1370. */
  1371. function validate_language_iso_name($lang_iso)
  1372. {
  1373. global $db;
  1374. $sql = 'SELECT lang_id
  1375. FROM ' . LANG_TABLE . "
  1376. WHERE lang_iso = '" . $db->sql_escape($lang_iso) . "'";
  1377. $result = $db->sql_query($sql);
  1378. $lang_id = (int) $db->sql_fetchfield('lang_id');
  1379. $db->sql_freeresult($result);
  1380. return ($lang_id) ? false : 'WRONG_DATA';
  1381. }
  1382. /**
  1383. * Validate Timezone Name
  1384. *
  1385. * Tests whether a timezone name is valid
  1386. *
  1387. * @param string $timezone The timezone string to test
  1388. *
  1389. * @return bool|string Either false if validation succeeded or
  1390. * a string which will be used as the error message
  1391. * (with the variable name appended)
  1392. */
  1393. function phpbb_validate_timezone($timezone)
  1394. {
  1395. return (in_array($timezone, phpbb_get_timezone_identifiers($timezone))) ? false : 'TIMEZONE_INVALID';
  1396. }
  1397. /**
  1398. * Check to see if the username has been taken, or if it is disallowed.
  1399. * Also checks if it includes the " character, which we don't allow in usernames.
  1400. * Used for registering, changing names, and posting anonymously with a username
  1401. *
  1402. * @param string $username The username to check
  1403. * @param string $allowed_username An allowed username, default being $user->data['username']
  1404. *
  1405. * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1406. */
  1407. function validate_username($username, $allowed_username = false)
  1408. {
  1409. global $config, $db, $user, $cache;
  1410. $clean_username = utf8_clean_string($username);
  1411. $allowed_username = ($allowed_username === false) ? $user->data['username_clean'] : utf8_clean_string($allowed_username);
  1412. if ($allowed_username == $clean_username)
  1413. {
  1414. return false;
  1415. }
  1416. // ... fast checks first.
  1417. if (strpos($username, '&quot;') !== false || strpos($username, '"') !== false || empty($clean_username))
  1418. {
  1419. return 'INVALID_CHARS';
  1420. }
  1421. $mbstring = $pcre = false;
  1422. // generic UTF-8 character types supported?
  1423. if (phpbb_pcre_utf8_support())
  1424. {
  1425. $pcre = true;
  1426. }
  1427. else if (function_exists('mb_ereg_match'))
  1428. {
  1429. mb_regex_encoding('UTF-8');
  1430. $mbstring = true;
  1431. }
  1432. switch ($config['allow_name_chars'])
  1433. {
  1434. case 'USERNAME_CHARS_ANY':
  1435. $pcre = true;
  1436. $regex = '.+';
  1437. break;
  1438. case 'USERNAME_ALPHA_ONLY':
  1439. $pcre = true;
  1440. $regex = '[A-Za-z0-9]+';
  1441. break;
  1442. case 'USERNAME_ALPHA_SPACERS':
  1443. $pcre = true;
  1444. $regex = '[A-Za-z0-9-[\]_+ ]+';
  1445. break;
  1446. case 'USERNAME_LETTER_NUM':
  1447. if ($pcre)
  1448. {
  1449. $regex = '[\p{Lu}\p{Ll}\p{N}]+';
  1450. }
  1451. else if ($mbstring)
  1452. {
  1453. $regex = '[[:upper:][:lower:][:digit:]]+';
  1454. }
  1455. else
  1456. {
  1457. $pcre = true;
  1458. $regex = '[a-zA-Z0-9]+';
  1459. }
  1460. break;
  1461. case 'USERNAME_LETTER_NUM_SPACERS':
  1462. if ($pcre)
  1463. {
  1464. $regex = '[-\]_+ [\p{Lu}\p{Ll}\p{N}]+';
  1465. }
  1466. else if ($mbstring)
  1467. {
  1468. $regex = '[-\]_+ \[[:upper:][:lower:][:digit:]]+';
  1469. }
  1470. else
  1471. {
  1472. $pcre = true;
  1473. $regex = '[-\]_+ [a-zA-Z0-9]+';
  1474. }
  1475. break;
  1476. case 'USERNAME_ASCII':
  1477. default:
  1478. $pcre = true;
  1479. $regex = '[\x01-\x7F]+';
  1480. break;
  1481. }
  1482. if ($pcre)
  1483. {
  1484. if (!preg_match('#^' . $regex . '$#u', $username))
  1485. {
  1486. return 'INVALID_CHARS';
  1487. }
  1488. }
  1489. else if ($mbstring)
  1490. {
  1491. mb_ereg_search_init($username, '^' . $regex . '$');
  1492. if (!mb_ereg_search())
  1493. {
  1494. return 'INVALID_CHARS';
  1495. }
  1496. }
  1497. $sql = 'SELECT username
  1498. FROM ' . USERS_TABLE . "
  1499. WHERE username_clean = '" . $db->sql_escape($clean_username) . "'";
  1500. $result = $db->sql_query($sql);
  1501. $row = $db->sql_fetchrow($result);
  1502. $db->sql_freeresult($result);
  1503. if ($row)
  1504. {
  1505. return 'USERNAME_TAKEN';
  1506. }
  1507. $sql = 'SELECT group_name
  1508. FROM ' . GROUPS_TABLE . "
  1509. WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($username)) . "'";
  1510. $result = $db->sql_query($sql);
  1511. $row = $db->sql_fetchrow($result);
  1512. $db->sql_freeresult($result);
  1513. if ($row)
  1514. {
  1515. return 'USERNAME_TAKEN';
  1516. }
  1517. $bad_usernames = $cache->obtain_disallowed_usernames();
  1518. foreach ($bad_usernames as $bad_username)
  1519. {
  1520. if (preg_match('#^' . $bad_username . '$#', $clean_username))
  1521. {
  1522. return 'USERNAME_DISALLOWED';
  1523. }
  1524. }
  1525. return false;
  1526. }
  1527. /**
  1528. * Check to see if the password meets the complexity settings
  1529. *
  1530. * @return boolean|string Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1531. */
  1532. function validate_password($password)
  1533. {
  1534. global $config;
  1535. if ($password === '' || $config['pass_complex'] === 'PASS_TYPE_ANY')
  1536. {
  1537. // Password empty or no password complexity required.
  1538. return false;
  1539. }
  1540. $pcre = $mbstring = false;
  1541. // generic UTF-8 character types supported?
  1542. if (phpbb_pcre_utf8_support())
  1543. {
  1544. $upp = '\p{Lu}';
  1545. $low = '\p{Ll}';
  1546. $num = '\p{N}';
  1547. $sym = '[^\p{Lu}\p{Ll}\p{N}]';
  1548. $pcre = true;
  1549. }
  1550. else if (function_exists('mb_ereg_match'))
  1551. {
  1552. mb_regex_encoding('UTF-8');
  1553. $upp = '[[:upper:]]';
  1554. $low = '[[:lower:]]';
  1555. $num = '[[:digit:]]';
  1556. $sym = '[^[:upper:][:lower:][:digit:]]';
  1557. $mbstring = true;
  1558. }
  1559. else
  1560. {
  1561. $upp = '[A-Z]';
  1562. $low = '[a-z]';
  1563. $num = '[0-9]';
  1564. $sym = '[^A-Za-z0-9]';
  1565. $pcre = true;
  1566. }
  1567. $chars = array();
  1568. switch ($config['pass_complex'])
  1569. {
  1570. // No break statements below ...
  1571. // We require strong passwords in case pass_complex is not set or is invalid
  1572. default:
  1573. // Require mixed case letters, numbers and symbols
  1574. case 'PASS_TYPE_SYMBOL':
  1575. $chars[] = $sym;
  1576. // Require mixed case letters and numbers
  1577. case 'PASS_TYPE_ALPHA':
  1578. $chars[] = $num;
  1579. // Require mixed case letters
  1580. case 'PASS_TYPE_CASE':
  1581. $chars[] = $low;
  1582. $chars[] = $upp;
  1583. }
  1584. if ($pcre)
  1585. {
  1586. foreach ($chars as $char)
  1587. {
  1588. if (!preg_match('#' . $char . '#u', $password))
  1589. {
  1590. return 'INVALID_CHARS';
  1591. }
  1592. }
  1593. }
  1594. else if ($mbstring)
  1595. {
  1596. foreach ($chars as $char)
  1597. {
  1598. if (mb_ereg($char, $password) === false)
  1599. {
  1600. return 'INVALID_CHARS';
  1601. }
  1602. }
  1603. }
  1604. return false;
  1605. }
  1606. /**
  1607. * Check to see if email address is a valid address and contains a MX record
  1608. *
  1609. * @param string $email The email to check
  1610. *
  1611. * @return mixed Either false if validation succeeded or a string which will be used as the error message (with the variable name appended)
  1612. */
  1613. function phpbb_validate_email($email, $config = null)
  1614. {
  1615. if ($config === null)
  1616. {
  1617. global $config;
  1618. }
  1619. $email = strtolower($email);
  1620. if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
  1621. {
  1622. return 'EMAIL_INVALID';
  1623. }
  1624. // Check MX record.
  1625. // The idea for this is from reading the UseBB blog/announcement. :)
  1626. if ($confi

Large files files are truncated, but you can click here to view the full file