PageRenderTime 77ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/functions_user.php

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

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