PageRenderTime 64ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/phpBB/includes/functions_user.php

https://github.com/Jipem/phpbb
PHP | 3532 lines | 2520 code | 532 blank | 480 comment | 457 complexity | 629b01b9312af82127b02b77723a871c MD5 | raw file
Possible License(s): AGPL-1.0

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

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