PageRenderTime 58ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/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
  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. function avatar_remote($data, &$error)
  1664. {
  1665. global $config, $db, $user, $phpbb_root_path, $phpEx;
  1666. if (!preg_match('#^(http|https|ftp)://#i', $data['remotelink']))
  1667. {
  1668. $data['remotelink'] = 'http://' . $data['remotelink'];
  1669. }
  1670. if (!preg_match('#^(http|https|ftp)://(?:(.*?\.)*?[a-z0-9\-]+?\.[a-z]{2,4}|(?:\d{1,3}\.){3,5}\d{1,3}):?([0-9]*?).*?\.(gif|jpg|jpeg|png)$#i', $data['remotelink']))
  1671. {
  1672. $error[] = $user->lang['AVATAR_URL_INVALID'];
  1673. return false;
  1674. }
  1675. // Make sure getimagesize works...
  1676. if (($image_data = @getimagesize($data['remotelink'])) === false && (empty($data['width']) || empty($data['height'])))
  1677. {
  1678. $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
  1679. return false;
  1680. }
  1681. if (!empty($image_data) && ($image_data[0] < 2 || $image_data[1] < 2))
  1682. {
  1683. $error[] = $user->lang['AVATAR_NO_SIZE'];
  1684. return false;
  1685. }
  1686. $width = ($data['width'] && $data['height']) ? $data['width'] : $image_data[0];
  1687. $height = ($data['width'] && $data['height']) ? $data['height'] : $image_data[1];
  1688. if ($width < 2 || $height < 2)
  1689. {
  1690. $error[] = $user->lang['AVATAR_NO_SIZE'];
  1691. return false;
  1692. }
  1693. // Check image type
  1694. include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
  1695. $types = fileupload::image_types();
  1696. $extension = strtolower(filespec::get_extension($data['remotelink']));
  1697. if (!empty($image_data) && (!isset($types[$image_data[2]]) || !in_array($extension, $types[$image_data[2]])))
  1698. {
  1699. if (!isset($types[$image_data[2]]))
  1700. {
  1701. $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
  1702. }
  1703. else
  1704. {
  1705. $error[] = sprintf($user->lang['IMAGE_FILETYPE_MISMATCH'], $types[$image_data[2]][0], $extension);
  1706. }
  1707. return false;
  1708. }
  1709. if ($config['avatar_max_width'] || $config['avatar_max_height'])
  1710. {
  1711. if ($width > $config['avatar_max_width'] || $height > $config['avatar_max_height'])
  1712. {
  1713. $error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $width, $height);
  1714. return false;
  1715. }
  1716. }
  1717. if ($config['avatar_min_width'] || $config['avatar_min_height'])
  1718. {
  1719. if ($width < $config['avatar_min_width'] || $height < $config['avatar_min_height'])
  1720. {
  1721. $error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $width, $height);
  1722. return false;
  1723. }
  1724. }
  1725. return array(AVATAR_REMOTE, $data['remotelink'], $width, $height);
  1726. }
  1727. /**
  1728. * Avatar upload using the upload class
  1729. */
  1730. function avatar_upload($data, &$error)
  1731. {
  1732. global $phpbb_root_path, $config, $db, $user, $phpEx;
  1733. // Init upload class
  1734. include_once($phpbb_root_path . 'includes/functions_upload.' . $phpEx);
  1735. $upload = new fileupload('AVATAR_', array('jpg', 'jpeg', 'gif', 'png'), $config['avatar_filesize'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], (isset($config['mime_triggers']) ? explode('|', $config['mime_triggers']) : false));
  1736. if (!empty($_FILES['uploadfile']['name']))
  1737. {
  1738. $file = $upload->form_upload('uploadfile');
  1739. }
  1740. else
  1741. {
  1742. $file = $upload->remote_upload($data['uploadurl']);
  1743. }
  1744. $prefix = $config['avatar_salt'] . '_';
  1745. $file->clean_filename('avatar', $prefix, $data['user_id']);
  1746. $destination = $config['avatar_path'];
  1747. // Adjust destination path (no trailing slash)
  1748. if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
  1749. {
  1750. $destination = substr($destination, 0, -1);
  1751. }
  1752. $destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
  1753. if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
  1754. {
  1755. $destination = '';
  1756. }
  1757. // Move file and overwrite any existing image
  1758. $file->move_file($destination, true);
  1759. if (sizeof($file->error))
  1760. {
  1761. $file->remove();
  1762. $error = array_merge($error, $file->error);
  1763. }
  1764. return array(AVATAR_UPLOAD, $data['user_id'] . '_' . time() . '.' . $file->get('extension'), $file->get('width'), $file->get('height'));
  1765. }
  1766. /**
  1767. * Generates avatar filename from the database entry
  1768. */
  1769. function get_avatar_filename($avatar_entry)
  1770. {
  1771. global $config;
  1772. if ($avatar_entry[0] === 'g')
  1773. {
  1774. $avatar_group = true;
  1775. $avatar_entry = substr($avatar_entry, 1);
  1776. }
  1777. else
  1778. {
  1779. $avatar_group = false;
  1780. }
  1781. $ext = substr(strrchr($avatar_entry, '.'), 1);
  1782. $avatar_entry = intval($avatar_entry);
  1783. return $config['avatar_salt'] . '_' . (($avatar_group) ? 'g' : '') . $avatar_entry . '.' . $ext;
  1784. }
  1785. /**
  1786. * Avatar Gallery
  1787. */
  1788. function avatar_gallery($category, $avatar_select, $items_per_column, $block_var = 'avatar_row')
  1789. {
  1790. global $user, $cache, $template;
  1791. global $config, $phpbb_root_path;
  1792. $avatar_list = array();
  1793. $path = $phpbb_root_path . $config['avatar_gallery_path'];
  1794. if (!file_exists($path) || !is_dir($path))
  1795. {
  1796. $avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
  1797. }
  1798. else
  1799. {
  1800. // Collect images
  1801. $dp = @opendir($path);
  1802. if (!$dp)
  1803. {
  1804. return array($user->lang['NO_AVATAR_CATEGORY'] => array());
  1805. }
  1806. while (($file = readdir($dp)) !== false)
  1807. {
  1808. if ($file[0] != '.' && preg_match('#^[^&"\'<>]+$#i', $file) && is_dir("$path/$file"))
  1809. {
  1810. $avatar_row_count = $avatar_col_count = 0;
  1811. if ($dp2 = @opendir("$path/$file"))
  1812. {
  1813. while (($sub_file = readdir($dp2)) !== false)
  1814. {
  1815. if (preg_match('#^[^&\'"<>]+\.(?:gif|png|jpe?g)$#i', $sub_file))
  1816. {
  1817. $avatar_list[$file][$avatar_row_count][$avatar_col_count] = array(
  1818. 'file' => rawurlencode($file) . '/' . rawurlencode($sub_file),
  1819. 'filename' => rawurlencode($sub_file),
  1820. 'name' => ucfirst(str_replace('_', ' ', preg_replace('#^(.*)\..*$#', '\1', $sub_file))),
  1821. );
  1822. $avatar_col_count++;
  1823. if ($avatar_col_count == $items_per_column)
  1824. {
  1825. $avatar_row_count++;
  1826. $avatar_col_count = 0;
  1827. }
  1828. }
  1829. }
  1830. closedir($dp2);
  1831. }
  1832. }
  1833. }
  1834. closedir($dp);
  1835. }
  1836. if (!sizeof($avatar_list))
  1837. {
  1838. $avatar_list = array($user->lang['NO_AVATAR_CATEGORY'] => array());
  1839. }
  1840. @ksort($avatar_list);
  1841. $category = (!$category) ? key($avatar_list) : $category;
  1842. $avatar_categories = array_keys($avatar_list);
  1843. $s_category_options = '';
  1844. foreach ($avatar_categories as $cat)
  1845. {
  1846. $s_category_options .= '<option value="' . $cat . '"' . (($cat == $category) ? ' selected="selected"' : '') . '>' . $cat . '</option>';
  1847. }
  1848. $template->assign_vars(array(
  1849. 'S_AVATARS_ENABLED' => true,
  1850. 'S_IN_AVATAR_GALLERY' => true,
  1851. 'S_CAT_OPTIONS' => $s_category_options)
  1852. );
  1853. $avatar_list = (isset($avatar_list[$category])) ? $avatar_list[$category] : array();
  1854. foreach ($avatar_list as $avatar_row_ary)
  1855. {
  1856. $template->assign_block_vars($block_var, array());
  1857. foreach ($avatar_row_ary as $avatar_col_ary)
  1858. {
  1859. $template->assign_block_vars($block_var . '.avatar_column', array(
  1860. 'AVATAR_IMAGE' => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
  1861. 'AVATAR_NAME' => $avatar_col_ary['name'],
  1862. 'AVATAR_FILE' => $avatar_col_ary['filename'])
  1863. );
  1864. $template->assign_block_vars($block_var . '.avatar_option_column', array(
  1865. 'AVATAR_IMAGE' => $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar_col_ary['file'],
  1866. 'S_OPTIONS_AVATAR' => $avatar_col_ary['filename'])
  1867. );
  1868. }
  1869. }
  1870. return $avatar_list;
  1871. }
  1872. /**
  1873. * Tries to (re-)establish avatar dimensions
  1874. */
  1875. function avatar_get_dimensions($avatar, $avatar_type, &$error, $current_x = 0, $current_y = 0)
  1876. {
  1877. global $config, $phpbb_root_path, $user;
  1878. switch ($avatar_type)
  1879. {
  1880. case AVATAR_REMOTE :
  1881. break;
  1882. case AVATAR_UPLOAD :
  1883. $avatar = $phpbb_root_path . $config['avatar_path'] . '/' . get_avatar_filename($avatar);
  1884. break;
  1885. case AVATAR_GALLERY :
  1886. $avatar = $phpbb_root_path . $config['avatar_gallery_path'] . '/' . $avatar ;
  1887. break;
  1888. }
  1889. // Make sure getimagesize works...
  1890. if (($image_data = @getimagesize($avatar)) === false)
  1891. {
  1892. $error[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
  1893. return false;
  1894. }
  1895. if ($image_data[0] < 2 || $image_data[1] < 2)
  1896. {
  1897. $error[] = $user->lang['AVATAR_NO_SIZE'];
  1898. return false;
  1899. }
  1900. // try to maintain ratio
  1901. if (!(empty($current_x) && empty($current_y)))
  1902. {
  1903. if ($current_x != 0)
  1904. {
  1905. $image_data[1] = (int) floor(($current_x / $image_data[0]) * $image_data[1]);
  1906. $image_data[1] = min($config['avatar_max_height'], $image_data[1]);
  1907. $image_data[1] = max($config['avatar_min_height'], $image_data[1]);
  1908. }
  1909. if ($current_y != 0)
  1910. {
  1911. $image_data[0] = (int) floor(($current_y / $image_data[1]) * $image_data[0]);
  1912. $image_data[0] = min($config['avatar_max_width'], $image_data[1]);
  1913. $image_data[0] = max($config['avatar_min_width'], $image_data[1]);
  1914. }
  1915. }
  1916. return array($image_data[0], $image_data[1]);
  1917. }
  1918. /**
  1919. * Uploading/Changing user avatar
  1920. */
  1921. function avatar_process_user(&$error, $custom_userdata = false, $can_upload = null)
  1922. {
  1923. global $config, $phpbb_root_path, $auth, $user, $db;
  1924. $data = array(
  1925. 'uploadurl' => request_var('uploadurl', ''),
  1926. 'remotelink' => request_var('remotelink', ''),
  1927. 'width' => request_var('width', 0),
  1928. 'height' => request_var('height', 0),
  1929. );
  1930. $error = validate_data($data, array(
  1931. 'uploadurl' => array('string', true, 5, 255),
  1932. 'remotelink' => array('string', true, 5, 255),
  1933. 'width' => array('string', true, 1, 3),
  1934. 'height' => array('string', true, 1, 3),
  1935. ));
  1936. if (sizeof($error))
  1937. {
  1938. return false;
  1939. }
  1940. $sql_ary = array();
  1941. if ($custom_userdata === false)
  1942. {
  1943. $userdata = &$user->data;
  1944. }
  1945. else
  1946. {
  1947. $userdata = &$custom_userdata;
  1948. }
  1949. $data['user_id'] = $userdata['user_id'];
  1950. $change_avatar = ($custom_userdata === false) ? $auth->acl_get('u_chgavatar') : true;
  1951. $avatar_select = basename(request_var('avatar_select', ''));
  1952. // Can we upload?
  1953. if (is_null($can_upload))
  1954. {
  1955. $can_upload = ($config['allow_avatar_upload'] && file_exists($phpbb_root_path . $config['avatar_path']) && phpbb_is_writable($phpbb_root_path . $config['avatar_path']) && $change_avatar && (@ini_get('file_uploads') || strtolower(@ini_get('file_uploads')) == 'on')) ? true : false;
  1956. }
  1957. if ((!empty($_FILES['uploadfile']['name']) || $data['uploadurl']) && $can_upload)
  1958. {
  1959. list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_upload($data, $error);
  1960. }
  1961. else if ($data['remotelink'] && $change_avatar && $config['allow_avatar_remote'])
  1962. {
  1963. list($sql_ary['user_avatar_type'], $sql_ary['user_avatar'], $sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = avatar_remote($data, $error);
  1964. }
  1965. else if ($avatar_select && $change_avatar && $config['allow_avatar_local'])
  1966. {
  1967. $category = basename(request_var('category', ''));
  1968. $sql_ary['user_avatar_type'] = AVATAR_GALLERY;
  1969. $sql_ary['user_avatar'] = $avatar_select;
  1970. // check avatar gallery
  1971. if (!is_dir($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category))
  1972. {
  1973. $sql_ary['user_avatar'] = '';
  1974. $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
  1975. }
  1976. else
  1977. {
  1978. list($sql_ary['user_avatar_width'], $sql_ary['user_avatar_height']) = getimagesize($phpbb_root_path . $config['avatar_gallery_path'] . '/' . $category . '/' . urldecode($sql_ary['user_avatar']));
  1979. $sql_ary['user_avatar'] = $category . '/' . $sql_ary['user_avatar'];
  1980. }
  1981. }
  1982. else if (isset($_POST['delete']) && $change_avatar)
  1983. {
  1984. $sql_ary['user_avatar'] = '';
  1985. $sql_ary['user_avatar_type'] = $sql_ary['user_avatar_width'] = $sql_ary['user_avatar_height'] = 0;
  1986. }
  1987. else if (!empty($userdata['user_avatar']))
  1988. {
  1989. // Only update the dimensions
  1990. if (empty($data['width']) || empty($data['height']))
  1991. {
  1992. if ($dims = avatar_get_dimensions($userdata['user_avatar'], $userdata['user_avatar_type'], $error, $data['width'], $data['height']))
  1993. {
  1994. list($guessed_x, $guessed_y) = $dims;
  1995. if (empty($data['width']))
  1996. {
  1997. $data['width'] = $guessed_x;
  1998. }
  1999. if (empty($data['height']))
  2000. {
  2001. $data['height'] = $guessed_y;
  2002. }
  2003. }
  2004. }
  2005. if (($config['avatar_max_width'] || $config['avatar_max_height']) &&
  2006. (($data['width'] != $userdata['user_avatar_width']) || $data['height'] != $userdata['user_avatar_height']))
  2007. {
  2008. if ($data['width'] > $config['avatar_max_width'] || $data['height'] > $config['avatar_max_height'])
  2009. {
  2010. $error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $data['width'], $data['height']);
  2011. }
  2012. }
  2013. if (!sizeof($error))
  2014. {
  2015. if ($config['avatar_min_width'] || $config['avatar_min_height'])
  2016. {
  2017. if ($data['width'] < $config['avatar_min_width'] || $data['height'] < $config['avatar_min_height'])
  2018. {
  2019. $error[] = sprintf($user->lang['AVATAR_WRONG_SIZE'], $config['avatar_min_width'], $config['avatar_min_height'], $config['avatar_max_width'], $config['avatar_max_height'], $data['width'], $data['height']);
  2020. }
  2021. }
  2022. }
  2023. if (!sizeof($error))
  2024. {
  2025. $sql_ary['user_avatar_width'] = $data['width'];
  2026. $sql_ary['user_avatar_height'] = $data['height'];
  2027. }
  2028. }
  2029. if (!sizeof($error))
  2030. {
  2031. // Do we actually have any data to update?
  2032. if (sizeof($sql_ary))
  2033. {
  2034. $ext_new = $ext_old = '';
  2035. if (isset($sql_ary['user_avatar']))
  2036. {
  2037. $userdata = ($custom_userdata === false) ? $user->data : $custom_userdata;
  2038. $ext_new = (empty($sql_ary['user_avatar'])) ? '' : substr(strrchr($sql_ary['user_avatar'], '.'), 1);
  2039. $ext_old = (empty($userdata['user_avatar'])) ? '' : substr(strrchr($userdata['user_avatar'], '.'), 1);
  2040. if ($userdata['user_avatar_type'] == AVATAR_UPLOAD)
  2041. {
  2042. // Delete old avatar if present
  2043. if ((!empty($userdata['user_avatar']) && empty($sql_ary['user_avatar']))
  2044. || ( !empty($userdata['user_avatar']) && !empty($sql_ary['user_avatar']) && $ext_new !== $ext_old))
  2045. {
  2046. avatar_delete('user', $userdata);
  2047. }
  2048. }
  2049. }
  2050. $sql = 'UPDATE ' . USERS_TABLE . '
  2051. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  2052. WHERE user_id = ' . (($custom_userdata === false) ? $user->data['user_id'] : $custom_userdata['user_id']);
  2053. $db->sql_query($sql);
  2054. }
  2055. }
  2056. return (sizeof($error)) ? false : true;
  2057. }
  2058. //
  2059. // Usergroup functions
  2060. //
  2061. /**
  2062. * Add or edit a group. If we're editing a group we only update user
  2063. * parameters such as rank, etc. if they are changed
  2064. */
  2065. function group_create(&$group_id, $type, $name, $desc, $group_attributes, $allow_desc_bbcode = false, $allow_desc_urls = false, $allow_desc_smilies = false)
  2066. {
  2067. global $phpbb_root_path, $config, $db, $user, $file_upload;
  2068. $error = array();
  2069. // Attributes which also affect the users table
  2070. $user_attribute_ary = array('group_colour', 'group_rank', 'group_avatar', 'group_avatar_type', 'group_avatar_width', 'group_avatar_height');
  2071. // Check data. Limit group name length.
  2072. if (!utf8_strlen($name) || utf8_strlen($name) > 60)
  2073. {
  2074. $error[] = (!utf8_strlen($name)) ? $user->lang['GROUP_ERR_USERNAME'] : $user->lang['GROUP_ERR_USER_LONG'];
  2075. }
  2076. $err = group_validate_groupname($group_id, $name);
  2077. if (!empty($err))
  2078. {
  2079. $error[] = $user->lang[$err];
  2080. }
  2081. if (!in_array($type, array(GROUP_OPEN, GROUP_CLOSED, GROUP_HIDDEN, GROUP_SPECIAL, GROUP_FREE)))
  2082. {
  2083. $error[] = $user->lang['GROUP_ERR_TYPE'];
  2084. }
  2085. if (!sizeof($error))
  2086. {
  2087. $user_ary = array();
  2088. $sql_ary = array(
  2089. 'group_name' => (string) $name,
  2090. 'group_desc' => (string) $desc,
  2091. 'group_desc_uid' => '',
  2092. 'group_desc_bitfield' => '',
  2093. 'group_type' => (int) $type,
  2094. );
  2095. // Parse description
  2096. if ($desc)
  2097. {
  2098. generate_text_for_storage($sql_ary['group_desc'], $sql_ary['group_desc_uid'], $sql_ary['group_desc_bitfield'], $sql_ary['group_desc_options'], $allow_desc_bbcode, $allow_desc_urls, $allow_desc_smilies);
  2099. }
  2100. if (sizeof($group_attributes))
  2101. {
  2102. // Merge them with $sql_ary to properly update the group
  2103. $sql_ary = array_merge($sql_ary, $group_attributes);
  2104. }
  2105. // Setting the log message before we set the group id (if group gets added)
  2106. $log = ($group_id) ? 'LOG_GROUP_UPDATED' : 'LOG_GROUP_CREATED';
  2107. $query = '';
  2108. if ($group_id)
  2109. {
  2110. $sql = 'SELECT user_id
  2111. FROM ' . USERS_TABLE . '
  2112. WHERE group_id = ' . $group_id;
  2113. $result = $db->sql_query($sql);
  2114. while ($row = $db->sql_fetchrow($result))
  2115. {
  2116. $user_ary[] = $row['user_id'];
  2117. }
  2118. $db->sql_freeresult($result);
  2119. if (isset($sql_ary['group_avatar']) && !$sql_ary['group_avatar'])
  2120. {
  2121. remove_default_avatar($group_id, $user_ary);
  2122. }
  2123. if (isset($sql_ary['group_rank']) && !$sql_ary['group_rank'])
  2124. {
  2125. remove_default_rank($group_id, $user_ary);
  2126. }
  2127. $sql = 'UPDATE ' . GROUPS_TABLE . '
  2128. SET ' . $db->sql_build_array('UPDATE', $sql_ary) . "
  2129. WHERE group_id = $group_id";
  2130. $db->sql_query($sql);
  2131. // Since we may update the name too, we need to do this on other tables too...
  2132. $sql = 'UPDATE ' . MODERATOR_CACHE_TABLE . "
  2133. SET group_name = '" . $db->sql_escape($sql_ary['group_name']) . "'
  2134. WHERE group_id = $group_id";
  2135. $db->sql_query($sql);
  2136. // One special case is the group skip auth setting. If this was changed we need to purge permissions for this group
  2137. if (isset($group_attributes['group_skip_auth']))
  2138. {
  2139. // Get users within this group...
  2140. $sql = 'SELECT user_id
  2141. FROM ' . USER_GROUP_TABLE . '
  2142. WHERE group_id = ' . $group_id . '
  2143. AND user_pending = 0';
  2144. $result = $db->sql_query($sql);
  2145. $user_id_ary = array();
  2146. while ($row = $db->sql_fetchrow($result))
  2147. {
  2148. $user_id_ary[] = $row['user_id'];
  2149. }
  2150. $db->sql_freeresult($result);
  2151. if (!empty($user_id_ary))
  2152. {
  2153. global $auth;
  2154. // Clear permissions cache of relevant users
  2155. $auth->acl_clear_prefetch($user_id_ary);
  2156. }
  2157. }
  2158. }
  2159. else
  2160. {
  2161. $sql = 'INSERT INTO ' . GROUPS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
  2162. $db->sql_query($sql);
  2163. }
  2164. if (!$group_id)
  2165. {
  2166. $group_id = $db->sql_nextid();
  2167. if (isset($sql_ary['group_avatar_type']) && $sql_ary['group_avatar_type'] == AVATAR_UPLOAD)
  2168. {
  2169. group_correct_avatar($group_id, $sql_ary['group_avatar']);
  2170. }
  2171. }
  2172. // Set user attributes
  2173. $sql_ary = array();
  2174. if (sizeof($group_attributes))
  2175. {
  2176. // Go through the user attributes array, check if a group attribute matches it and then set it. ;)
  2177. foreach ($user_attribute_ary as $attribute)
  2178. {
  2179. if (!isset($group_attributes[$attribute]))
  2180. {
  2181. continue;
  2182. }
  2183. // If we are about to set an avatar, we will not overwrite user avatars if no group avatar is set...
  2184. if (strpos($attribute, 'group_avatar') === 0 && !$group_attributes[$attribute])
  2185. {
  2186. continue;
  2187. }
  2188. $sql_ary[$attribute] = $group_attributes[$attribute];
  2189. }
  2190. }
  2191. if (sizeof($sql_ary) && sizeof($user_ary))
  2192. {
  2193. group_set_user_default($group_id, $user_ary, $sql_ary);
  2194. }
  2195. $name = ($type == GROUP_SPECIAL) ? $user->lang['G_' . $name] : $name;
  2196. add_log('admin', $log, $name);
  2197. group_update_listings($group_id);
  2198. }
  2199. return (sizeof($error)) ? $error : false;
  2200. }
  2201. /**
  2202. * Changes a group avatar's filename to conform to the naming scheme
  2203. */
  2204. function group_correct_avatar($group_id, $old_entry)
  2205. {
  2206. global $config, $db, $phpbb_root_path;
  2207. $group_id = (int)$group_id;
  2208. $ext = substr(strrchr($old_entry, '.'), 1);
  2209. $old_filename = get_avatar_filename($old_entry);
  2210. $new_filename = $config['avatar_salt'] . "_g$group_id.$ext";
  2211. $new_entry = 'g' . $group_id . '_' . substr(time(), -5) . ".$ext";
  2212. $avatar_path = $phpbb_root_path . $config['avatar_path'];
  2213. if (@rename($avatar_path . '/'. $old_filename, $avatar_path . '/' . $new_filename))
  2214. {
  2215. $sql = 'UPDATE ' . GROUPS_TABLE . '
  2216. SET group_avatar = \'' . $db->sql_escape($new_entry) . "'
  2217. WHERE group_id = $group_id";
  2218. $db->sql_query($sql);
  2219. }
  2220. }
  2221. /**
  2222. * Remove avatar also for users not having the group as default
  2223. */
  2224. function avatar_remove_db($avatar_name)
  2225. {
  2226. global $config, $db;
  2227. $sql = 'UPDATE ' . USERS_TABLE . "
  2228. SET user_avatar = '',
  2229. user_avatar_type = 0
  2230. WHERE user_avatar = '" . $db->sql_escape($avatar_name) . '\'';
  2231. $db->sql_query($sql);
  2232. }
  2233. /**
  2234. * Group Delete
  2235. */
  2236. function group_delete($group_id, $group_name = false)
  2237. {
  2238. global $db, $phpbb_root_path, $phpEx;
  2239. if (!$group_name)
  2240. {
  2241. $group_name = get_group_name($group_id);
  2242. }
  2243. $start = 0;
  2244. do
  2245. {
  2246. $user_id_ary = $username_ary = array();
  2247. // Batch query for group members, call group_user_del
  2248. $sql = 'SELECT u.user_id, u.username
  2249. FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . " u
  2250. WHERE ug.group_id = $group_id
  2251. AND u.user_id = ug.user_id";
  2252. $result = $db->sql_query_limit($sql, 200, $start);
  2253. if ($row = $db->sql_fetchrow($result))
  2254. {
  2255. do
  2256. {
  2257. $user_id_ary[] = $row['user_id'];
  2258. $username_ary[] = $row['username'];
  2259. $start++;
  2260. }
  2261. while ($row = $db->sql_fetchrow($result));
  2262. group_user_del($group_id, $user_id_ary, $username_ary, $group_name);
  2263. }
  2264. else
  2265. {
  2266. $start = 0;
  2267. }
  2268. $db->sql_freeresult($result);
  2269. }
  2270. while ($start);
  2271. // Delete group
  2272. $sql = 'DELETE FROM ' . GROUPS_TABLE . "
  2273. WHERE group_id = $group_id";
  2274. $db->sql_query($sql);
  2275. // Delete auth entries from the groups table
  2276. $sql = 'DELETE FROM ' . ACL_GROUPS_TABLE . "
  2277. WHERE group_id = $group_id";
  2278. $db->sql_query($sql);
  2279. // Re-cache moderators
  2280. if (!function_exists('cache_moderators'))
  2281. {
  2282. include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
  2283. }
  2284. cache_moderators();
  2285. add_log('admin', 'LOG_GROUP_DELETE', $group_name);
  2286. // Return false - no error
  2287. return false;
  2288. }
  2289. /**
  2290. * Add user(s) to group
  2291. *
  2292. * @return mixed false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
  2293. */
  2294. function group_user_add($group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $default = false, $leader = 0, $pending = 0, $group_attributes = false)
  2295. {
  2296. global $db, $auth;
  2297. // We need both username and user_id info
  2298. $result = user_get_id_name($user_id_ary, $username_ary);
  2299. if (!sizeof($user_id_ary) || $result !== false)
  2300. {
  2301. return 'NO_USER';
  2302. }
  2303. // Remove users who are already members of this group
  2304. $sql = 'SELECT user_id, group_leader
  2305. FROM ' . USER_GROUP_TABLE . '
  2306. WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . "
  2307. AND group_id = $group_id";
  2308. $result = $db->sql_query($sql);
  2309. $add_id_ary = $update_id_ary = array();
  2310. while ($row = $db->sql_fetchrow($result))
  2311. {
  2312. $add_id_ary[] = (int) $row['user_id'];
  2313. if ($leader && !$row['group_leader'])
  2314. {
  2315. $update_id_ary[] = (int) $row['user_id'];
  2316. }
  2317. }
  2318. $db->sql_freeresult($result);
  2319. // Do all the users exist in this group?
  2320. $add_id_ary = array_diff($user_id_ary, $add_id_ary);
  2321. // If we have no users
  2322. if (!sizeof($add_id_ary) && !sizeof($update_id_ary))
  2323. {
  2324. return 'GROUP_USERS_EXIST';
  2325. }
  2326. $db->sql_transaction('begin');
  2327. // Insert the new users
  2328. if (sizeof($add_id_ary))
  2329. {
  2330. $sql_ary = array();
  2331. foreach ($add_id_ary as $user_id)
  2332. {
  2333. $sql_ary[] = array(
  2334. 'user_id' => (int) $user_id,
  2335. 'group_id' => (int) $group_id,
  2336. 'group_leader' => (int) $leader,
  2337. 'user_pending' => (int) $pending,
  2338. );
  2339. }
  2340. $db->sql_multi_insert(USER_GROUP_TABLE, $sql_ary);
  2341. }
  2342. if (sizeof($update_id_ary))
  2343. {
  2344. $sql = 'UPDATE ' . USER_GROUP_TABLE . '
  2345. SET group_leader = 1
  2346. WHERE ' . $db->sql_in_set('user_id', $update_id_ary) . "
  2347. AND group_id = $group_id";
  2348. $db->sql_query($sql);
  2349. }
  2350. if ($default)
  2351. {
  2352. group_user_attributes('default', $group_id, $user_id_ary, false, $group_name, $group_attributes);
  2353. }
  2354. $db->sql_transaction('commit');
  2355. // Clear permissions cache of relevant users
  2356. $auth->acl_clear_prefetch($user_id_ary);
  2357. if (!$group_name)
  2358. {
  2359. $group_name = get_group_name($group_id);
  2360. }
  2361. $log = ($leader) ? 'LOG_MODS_ADDED' : (($pending) ? 'LOG_USERS_PENDING' : 'LOG_USERS_ADDED');
  2362. add_log('admin', $log, $group_name, implode(', ', $username_ary));
  2363. group_update_listings($group_id);
  2364. // Return false - no error
  2365. return false;
  2366. }
  2367. /**
  2368. * Remove a user/s from a given group. When we remove users we update their
  2369. * default group_id. We do this by examining which "special" groups they belong
  2370. * to. The selection is made based on a reasonable priority system
  2371. *
  2372. * @return false if no errors occurred, else the user lang string for the relevant error, for example 'NO_USER'
  2373. */
  2374. function group_user_del($group_id, $user_id_ary = false, $username_ary = false, $group_name = false)
  2375. {
  2376. global $db, $auth, $config;
  2377. if ($config['coppa_enable'])
  2378. {
  2379. $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED_COPPA', 'REGISTERED', 'BOTS', 'GUESTS');
  2380. }
  2381. else
  2382. {
  2383. $group_order = array('ADMINISTRATORS', 'GLOBAL_MODERATORS', 'NEWLY_REGISTERED', 'REGISTERED', 'BOTS', 'GUESTS');
  2384. }
  2385. // We need both username and user_id info
  2386. $result = user_get_id_name($user_id_ary, $username_ary);
  2387. if (!sizeof($user_id_ary) || $result !== false)
  2388. {
  2389. return 'NO_USER';
  2390. }
  2391. $sql = 'SELECT *
  2392. FROM ' . GROUPS_TABLE . '
  2393. WHERE ' . $db->sql_in_set('group_name', $group_order);
  2394. $result = $db->sql_query($sql);
  2395. $group_order_id = $special_group_data = array();
  2396. while ($row = $db->sql_fetchrow($result))
  2397. {
  2398. $group_order_id[$row['group_name']] = $row['group_id'];
  2399. $special_group_data[$row['group_id']] = array(
  2400. 'group_colour' => $row['group_colour'],
  2401. 'group_rank' => $row['group_rank'],
  2402. );
  2403. // Only set the group avatar if one is defined...
  2404. if ($row['group_avatar'])
  2405. {
  2406. $special_group_data[$row['group_id']] = array_merge($special_group_data[$row['group_id']], array(
  2407. 'group_avatar' => $row['group_avatar'],
  2408. 'group_avatar_type' => $row['group_avatar_type'],
  2409. 'group_avatar_width' => $row['group_avatar_width'],
  2410. 'group_avatar_height' => $row['group_avatar_height'])
  2411. );
  2412. }
  2413. }
  2414. $db->sql_freeresult($result);
  2415. // Get users default groups - we only need to reset default group membership if the group from which the user gets removed is set as default
  2416. $sql = 'SELECT user_id, group_id
  2417. FROM ' . USERS_TABLE . '
  2418. WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
  2419. $result = $db->sql_query($sql);
  2420. $default_groups = array();
  2421. while ($row = $db->sql_fetchrow($result))
  2422. {
  2423. $default_groups[$row['user_id']] = $row['group_id'];
  2424. }
  2425. $db->sql_freeresult($result);
  2426. // What special group memberships exist for these users?
  2427. $sql = 'SELECT g.group_id, g.group_name, ug.user_id
  2428. FROM ' . USER_GROUP_TABLE . ' ug, ' . GROUPS_TABLE . ' g
  2429. WHERE ' . $db->sql_in_set('ug.user_id', $user_id_ary) . "
  2430. AND g.group_id = ug.group_id
  2431. AND g.group_id <> $group_id
  2432. AND g.group_type = " . GROUP_SPECIAL . '
  2433. ORDER BY ug.user_id, g.group_id';
  2434. $result = $db->sql_query($sql);
  2435. $temp_ary = array();
  2436. while ($row = $db->sql_fetchrow($result))
  2437. {
  2438. if ($default_groups[$row['user_id']] == $group_id && (!isset($temp_ary[$row['user_id']]) || $group_order_id[$row['group_name']] < $temp_ary[$row['user_id']]))
  2439. {
  2440. $temp_ary[$row['user_id']] = $row['group_id'];
  2441. }
  2442. }
  2443. $db->sql_freeresult($result);
  2444. // sql_where_ary holds the new default groups and their users
  2445. $sql_where_ary = array();
  2446. foreach ($temp_ary as $uid => $gid)
  2447. {
  2448. $sql_where_ary[$gid][] = $uid;
  2449. }
  2450. unset($temp_ary);
  2451. foreach ($special_group_data as $gid => $default_data_ary)
  2452. {
  2453. if (isset($sql_where_ary[$gid]) && sizeof($sql_where_ary[$gid]))
  2454. {
  2455. remove_default_rank($group_id, $sql_where_ary[$gid]);
  2456. remove_default_avatar($group_id, $sql_where_ary[$gid]);
  2457. group_set_user_default($gid, $sql_where_ary[$gid], $default_data_ary);
  2458. }
  2459. }
  2460. unset($special_group_data);
  2461. $sql = 'DELETE FROM ' . USER_GROUP_TABLE . "
  2462. WHERE group_id = $group_id
  2463. AND " . $db->sql_in_set('user_id', $user_id_ary);
  2464. $db->sql_query($sql);
  2465. // Clear permissions cache of relevant users
  2466. $auth->acl_clear_prefetch($user_id_ary);
  2467. if (!$group_name)
  2468. {
  2469. $group_name = get_group_name($group_id);
  2470. }
  2471. $log = 'LOG_GROUP_REMOVE';
  2472. if ($group_name)
  2473. {
  2474. add_log('admin', $log, $group_name, implode(', ', $username_ary));
  2475. }
  2476. group_update_listings($group_id);
  2477. // Return false - no error
  2478. return false;
  2479. }
  2480. /**
  2481. * Removes the group avatar of the default group from the users in user_ids who have that group as default.
  2482. */
  2483. function remove_default_avatar($group_id, $user_ids)
  2484. {
  2485. global $db;
  2486. if (!is_array($user_ids))
  2487. {
  2488. $user_ids = array($user_ids);
  2489. }
  2490. if (empty($user_ids))
  2491. {
  2492. return false;
  2493. }
  2494. $user_ids = array_map('intval', $user_ids);
  2495. $sql = 'SELECT *
  2496. FROM ' . GROUPS_TABLE . '
  2497. WHERE group_id = ' . (int)$group_id;
  2498. $result = $db->sql_query($sql);
  2499. if (!$row = $db->sql_fetchrow($result))
  2500. {
  2501. $db->sql_freeresult($result);
  2502. return false;
  2503. }
  2504. $db->sql_freeresult($result);
  2505. $sql = 'UPDATE ' . USERS_TABLE . "
  2506. SET user_avatar = '',
  2507. user_avatar_type = 0,
  2508. user_avatar_width = 0,
  2509. user_avatar_height = 0
  2510. WHERE group_id = " . (int) $group_id . "
  2511. AND user_avatar = '" . $db->sql_escape($row['group_avatar']) . "'
  2512. AND " . $db->sql_in_set('user_id', $user_ids);
  2513. $db->sql_query($sql);
  2514. }
  2515. /**
  2516. * Removes the group rank of the default group from the users in user_ids who have that group as default.
  2517. */
  2518. function remove_default_rank($group_id, $user_ids)
  2519. {
  2520. global $db;
  2521. if (!is_array($user_ids))
  2522. {
  2523. $user_ids = array($user_ids);
  2524. }
  2525. if (empty($user_ids))
  2526. {
  2527. return false;
  2528. }
  2529. $user_ids = array_map('intval', $user_ids);
  2530. $sql = 'SELECT *
  2531. FROM ' . GROUPS_TABLE . '
  2532. WHERE group_id = ' . (int)$group_id;
  2533. $result = $db->sql_query($sql);
  2534. if (!$row = $db->sql_fetchrow($result))
  2535. {
  2536. $db->sql_freeresult($result);
  2537. return false;
  2538. }
  2539. $db->sql_freeresult($result);
  2540. $sql = 'UPDATE ' . USERS_TABLE . '
  2541. SET user_rank = 0
  2542. WHERE group_id = ' . (int)$group_id . '
  2543. AND user_rank <> 0
  2544. AND user_rank = ' . (int)$row['group_rank'] . '
  2545. AND ' . $db->sql_in_set('user_id', $user_ids);
  2546. $db->sql_query($sql);
  2547. }
  2548. /**
  2549. * This is used to promote (to leader), demote or set as default a member/s
  2550. */
  2551. function group_user_attributes($action, $group_id, $user_id_ary = false, $username_ary = false, $group_name = false, $group_attributes = false)
  2552. {
  2553. global $db, $auth, $phpbb_root_path, $phpEx, $config;
  2554. // We need both username and user_id info
  2555. $result = user_get_id_name($user_id_ary, $username_ary);
  2556. if (!sizeof($user_id_ary) || $result !== false)
  2557. {
  2558. return 'NO_USERS';
  2559. }
  2560. if (!$group_name)
  2561. {
  2562. $group_name = get_group_name($group_id);
  2563. }
  2564. switch ($action)
  2565. {
  2566. case 'demote':
  2567. case 'promote':
  2568. $sql = 'SELECT user_id FROM ' . USER_GROUP_TABLE . "
  2569. WHERE group_id = $group_id
  2570. AND user_pending = 1
  2571. AND " . $db->sql_in_set('user_id', $user_id_ary);
  2572. $result = $db->sql_query_limit($sql, 1);
  2573. $not_empty = ($db->sql_fetchrow($result));
  2574. $db->sql_freeresult($result);
  2575. if ($not_empty)
  2576. {
  2577. return 'NO_VALID_USERS';
  2578. }
  2579. $sql = 'UPDATE ' . USER_GROUP_TABLE . '
  2580. SET group_leader = ' . (($action == 'promote') ? 1 : 0) . "
  2581. WHERE group_id = $group_id
  2582. AND user_pending = 0
  2583. AND " . $db->sql_in_set('user_id', $user_id_ary);
  2584. $db->sql_query($sql);
  2585. $log = ($action == 'promote') ? 'LOG_GROUP_PROMOTED' : 'LOG_GROUP_DEMOTED';
  2586. break;
  2587. case 'approve':
  2588. // Make sure we only approve those which are pending ;)
  2589. $sql = 'SELECT u.user_id, u.user_email, u.username, u.username_clean, u.user_notify_type, u.user_jabber, u.user_lang
  2590. FROM ' . USERS_TABLE . ' u, ' . USER_GROUP_TABLE . ' ug
  2591. WHERE ug.group_id = ' . $group_id . '
  2592. AND ug.user_pending = 1
  2593. AND ug.user_id = u.user_id
  2594. AND ' . $db->sql_in_set('ug.user_id', $user_id_ary);
  2595. $result = $db->sql_query($sql);
  2596. $user_id_ary = $email_users = array();
  2597. while ($row = $db->sql_fetchrow($result))
  2598. {
  2599. $user_id_ary[] = $row['user_id'];
  2600. $email_users[] = $row;
  2601. }
  2602. $db->sql_freeresult($result);
  2603. if (!sizeof($user_id_ary))
  2604. {
  2605. return false;
  2606. }
  2607. $sql = 'UPDATE ' . USER_GROUP_TABLE . "
  2608. SET user_pending = 0
  2609. WHERE group_id = $group_id
  2610. AND " . $db->sql_in_set('user_id', $user_id_ary);
  2611. $db->sql_query($sql);
  2612. // Send approved email to users...
  2613. include_once($phpbb_root_path . 'includes/functions_messenger.' . $phpEx);
  2614. $messenger = new messenger();
  2615. foreach ($email_users as $row)
  2616. {
  2617. $messenger->template('group_approved', $row['user_lang']);
  2618. $messenger->to($row['user_email'], $row['username']);
  2619. $messenger->im($row['user_jabber'], $row['username']);
  2620. $messenger->assign_vars(array(
  2621. 'USERNAME' => htmlspecialchars_decode($row['username']),
  2622. 'GROUP_NAME' => htmlspecialchars_decode($group_name),
  2623. 'U_GROUP' => generate_board_url() . "/ucp.$phpEx?i=groups&mode=membership")
  2624. );
  2625. $messenger->send($row['user_notify_type']);
  2626. }
  2627. $messenger->save_queue();
  2628. $log = 'LOG_USERS_APPROVED';
  2629. break;
  2630. case 'default':
  2631. // We only set default group for approved members of the group
  2632. $sql = 'SELECT user_id
  2633. FROM ' . USER_GROUP_TABLE . "
  2634. WHERE group_id = $group_id
  2635. AND user_pending = 0
  2636. AND " . $db->sql_in_set('user_id', $user_id_ary);
  2637. $result = $db->sql_query($sql);
  2638. $user_id_ary = $username_ary = array();
  2639. while ($row = $db->sql_fetchrow($result))
  2640. {
  2641. $user_id_ary[] = $row['user_id'];
  2642. }
  2643. $db->sql_freeresult($result);
  2644. $result = user_get_id_name($user_id_ary, $username_ary);
  2645. if (!sizeof($user_id_ary) || $result !== false)
  2646. {
  2647. return 'NO_USERS';
  2648. }
  2649. $sql = 'SELECT user_id, group_id FROM ' . USERS_TABLE . '
  2650. WHERE ' . $db->sql_in_set('user_id', $user_id_ary, false, true);
  2651. $result = $db->sql_query($sql);
  2652. $groups = array();
  2653. while ($row = $db->sql_fetchrow($result))
  2654. {
  2655. if (!isset($groups[$row['group_id']]))
  2656. {
  2657. $groups[$row['group_id']] = array();
  2658. }
  2659. $groups[$row['group_id']][] = $row['user_id'];
  2660. }
  2661. $db->sql_freeresult($result);
  2662. foreach ($groups as $gid => $uids)
  2663. {
  2664. remove_default_rank($gid, $uids);
  2665. remove_default_avatar($gid, $uids);
  2666. }
  2667. group_set_user_default($group_id, $user_id_ary, $group_attributes);
  2668. $log = 'LOG_GROUP_DEFAULTS';
  2669. break;
  2670. }
  2671. // Clear permissions cache of relevant users
  2672. $auth->acl_clear_prefetch($user_id_ary);
  2673. add_log('admin', $log, $group_name, implode(', ', $username_ary));
  2674. group_update_listings($group_id);
  2675. return false;
  2676. }
  2677. /**
  2678. * A small version of validate_username to check for a group name's existence. To be called directly.
  2679. */
  2680. function group_validate_groupname($group_id, $group_name)
  2681. {
  2682. global $config, $db;
  2683. $group_name = utf8_clean_string($group_name);
  2684. if (!empty($group_id))
  2685. {
  2686. $sql = 'SELECT group_name
  2687. FROM ' . GROUPS_TABLE . '
  2688. WHERE group_id = ' . (int) $group_id;
  2689. $result = $db->sql_query($sql);
  2690. $row = $db->sql_fetchrow($result);
  2691. $db->sql_freeresult($result);
  2692. if (!$row)
  2693. {
  2694. return false;
  2695. }
  2696. $allowed_groupname = utf8_clean_string($row['group_name']);
  2697. if ($allowed_groupname == $group_name)
  2698. {
  2699. return false;
  2700. }
  2701. }
  2702. $sql = 'SELECT group_name
  2703. FROM ' . GROUPS_TABLE . "
  2704. WHERE LOWER(group_name) = '" . $db->sql_escape(utf8_strtolower($group_name)) . "'";
  2705. $result = $db->sql_query($sql);
  2706. $row = $db->sql_fetchrow($result);
  2707. $db->sql_freeresult($result);
  2708. if ($row)
  2709. {
  2710. return 'GROUP_NAME_TAKEN';
  2711. }
  2712. return false;
  2713. }
  2714. /**
  2715. * Set users default group
  2716. *
  2717. * @access private
  2718. */
  2719. function group_set_user_default($group_id, $user_id_ary, $group_attributes = false, $update_listing = false)
  2720. {
  2721. global $cache, $db;
  2722. if (empty($user_id_ary))
  2723. {
  2724. return;
  2725. }
  2726. $attribute_ary = array(
  2727. 'group_colour' => 'string',
  2728. 'group_rank' => 'int',
  2729. 'group_avatar' => 'string',
  2730. 'group_avatar_type' => 'int',
  2731. 'group_avatar_width' => 'int',
  2732. 'group_avatar_height' => 'int',
  2733. );
  2734. $sql_ary = array(
  2735. 'group_id' => $group_id
  2736. );
  2737. // Were group attributes passed to the function? If not we need to obtain them
  2738. if ($group_attributes === false)
  2739. {
  2740. $sql = 'SELECT ' . implode(', ', array_keys($attribute_ary)) . '
  2741. FROM ' . GROUPS_TABLE . "
  2742. WHERE group_id = $group_id";
  2743. $result = $db->sql_query($sql);
  2744. $group_attributes = $db->sql_fetchrow($result);
  2745. $db->sql_freeresult($result);
  2746. }
  2747. foreach ($attribute_ary as $attribute => $type)
  2748. {
  2749. if (isset($group_attributes[$attribute]))
  2750. {
  2751. // If we are about to set an avatar or rank, we will not overwrite with empty, unless we are not actually changing the default group
  2752. if ((strpos($attribute, 'group_avatar') === 0 || strpos($attribute, 'group_rank') === 0) && !$group_attributes[$attribute])
  2753. {
  2754. continue;
  2755. }
  2756. settype($group_attributes[$attribute], $type);
  2757. $sql_ary[str_replace('group_', 'user_', $attribute)] = $group_attributes[$attribute];
  2758. }
  2759. }
  2760. // Before we update the user attributes, we will make a list of those having now the group avatar assigned
  2761. if (isset($sql_ary['user_avatar']))
  2762. {
  2763. // Ok, get the original avatar data from users having an uploaded one (we need to remove these from the filesystem)
  2764. $sql = 'SELECT user_id, group_id, user_avatar
  2765. FROM ' . USERS_TABLE . '
  2766. WHERE ' . $db->sql_in_set('user_id', $user_id_ary) . '
  2767. AND user_avatar_type = ' . AVATAR_UPLOAD;
  2768. $result = $db->sql_query($sql);
  2769. while ($row = $db->sql_fetchrow($result))
  2770. {
  2771. avatar_delete('user', $row);
  2772. }
  2773. $db->sql_freeresult($result);
  2774. }
  2775. else
  2776. {
  2777. unset($sql_ary['user_avatar_type']);
  2778. unset($sql_ary['user_avatar_height']);
  2779. unset($sql_ary['user_avatar_width']);
  2780. }
  2781. $sql = 'UPDATE ' . USERS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $sql_ary) . '
  2782. WHERE ' . $db->sql_in_set('user_id', $user_id_ary);
  2783. $db->sql_query($sql);
  2784. if (isset($sql_ary['user_colour']))
  2785. {
  2786. // Update any cached colour information for these users
  2787. $sql = 'UPDATE ' . FORUMS_TABLE . " SET forum_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
  2788. WHERE " . $db->sql_in_set('forum_last_poster_id', $user_id_ary);
  2789. $db->sql_query($sql);
  2790. $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_first_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
  2791. WHERE " . $db->sql_in_set('topic_poster', $user_id_ary);
  2792. $db->sql_query($sql);
  2793. $sql = 'UPDATE ' . TOPICS_TABLE . " SET topic_last_poster_colour = '" . $db->sql_escape($sql_ary['user_colour']) . "'
  2794. WHERE " . $db->sql_in_set('topic_last_poster_id', $user_id_ary);
  2795. $db->sql_query($sql);
  2796. global $config;
  2797. if (in_array($config['newest_user_id'], $user_id_ary))
  2798. {
  2799. set_config('newest_user_colour', $sql_ary['user_colour'], true);
  2800. }
  2801. }
  2802. if ($update_listing)
  2803. {
  2804. group_update_listings($group_id);
  2805. }
  2806. // Because some tables/caches use usercolour-specific data we need to purge this here.
  2807. $cache->destroy('sql', MODERATOR_CACHE_TABLE);
  2808. }
  2809. /**
  2810. * Get group name
  2811. */
  2812. function get_group_name($group_id)
  2813. {
  2814. global $db, $user;
  2815. $sql = 'SELECT group_name, group_type
  2816. FROM ' . GROUPS_TABLE . '
  2817. WHERE group_id = ' . (int) $group_id;
  2818. $result = $db->sql_query($sql);
  2819. $row = $db->sql_fetchrow($result);
  2820. $db->sql_freeresult($result);
  2821. if (!$row || ($row['group_type'] == GROUP_SPECIAL && empty($user->lang)))
  2822. {
  2823. return '';
  2824. }
  2825. return ($row['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $row['group_name']] : $row['group_name'];
  2826. }
  2827. /**
  2828. * Obtain either the members of a specified group, the groups the specified user is subscribed to
  2829. * or checking if a specified user is in a specified group. This function does not return pending memberships.
  2830. *
  2831. * Note: Never use this more than once... first group your users/groups
  2832. */
  2833. function group_memberships($group_id_ary = false, $user_id_ary = false, $return_bool = false)
  2834. {
  2835. global $db;
  2836. if (!$group_id_ary && !$user_id_ary)
  2837. {
  2838. return true;
  2839. }
  2840. if ($user_id_ary)
  2841. {
  2842. $user_id_ary = (!is_array($user_id_ary)) ? array($user_id_ary) : $user_id_ary;
  2843. }
  2844. if ($group_id_ary)
  2845. {
  2846. $group_id_ary = (!is_array($group_id_ary)) ? array($group_id_ary) : $group_id_ary;
  2847. }
  2848. $sql = 'SELECT ug.*, u.username, u.username_clean, u.user_email
  2849. FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . ' u
  2850. WHERE ug.user_id = u.user_id
  2851. AND ug.user_pending = 0 AND ';
  2852. if ($group_id_ary)
  2853. {
  2854. $sql .= ' ' . $db->sql_in_set('ug.group_id', $group_id_ary);
  2855. }
  2856. if ($user_id_ary)
  2857. {
  2858. $sql .= ($group_id_ary) ? ' AND ' : ' ';
  2859. $sql .= $db->sql_in_set('ug.user_id', $user_id_ary);
  2860. }
  2861. $result = ($return_bool) ? $db->sql_query_limit($sql, 1) : $db->sql_query($sql);
  2862. $row = $db->sql_fetchrow($result);
  2863. if ($return_bool)
  2864. {
  2865. $db->sql_freeresult($result);
  2866. return ($row) ? true : false;
  2867. }
  2868. if (!$row)
  2869. {
  2870. return false;
  2871. }
  2872. $return = array();
  2873. do
  2874. {
  2875. $return[] = $row;
  2876. }
  2877. while ($row = $db->sql_fetchrow($result));
  2878. $db->sql_freeresult($result);
  2879. return $return;
  2880. }
  2881. /**
  2882. * Re-cache moderators and foes if group has a_ or m_ permissions
  2883. */
  2884. function group_update_listings($group_id)
  2885. {
  2886. global $auth;
  2887. $hold_ary = $auth->acl_group_raw_data($group_id, array('a_', 'm_'));
  2888. if (!sizeof($hold_ary))
  2889. {
  2890. return;
  2891. }
  2892. $mod_permissions = $admin_permissions = false;
  2893. foreach ($hold_ary as $g_id => $forum_ary)
  2894. {
  2895. foreach ($forum_ary as $forum_id => $auth_ary)
  2896. {
  2897. foreach ($auth_ary as $auth_option => $setting)
  2898. {
  2899. if ($mod_permissions && $admin_permissions)
  2900. {
  2901. break 3;
  2902. }
  2903. if ($setting != ACL_YES)
  2904. {
  2905. continue;
  2906. }
  2907. if ($auth_option == 'm_')
  2908. {
  2909. $mod_permissions = true;
  2910. }
  2911. if ($auth_option == 'a_')
  2912. {
  2913. $admin_permissions = true;
  2914. }
  2915. }
  2916. }
  2917. }
  2918. if ($mod_permissions)
  2919. {
  2920. if (!function_exists('cache_moderators'))
  2921. {
  2922. global $phpbb_root_path, $phpEx;
  2923. include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
  2924. }
  2925. cache_moderators();
  2926. }
  2927. if ($mod_permissions || $admin_permissions)
  2928. {
  2929. if (!function_exists('update_foes'))
  2930. {
  2931. global $phpbb_root_path, $phpEx;
  2932. include($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
  2933. }
  2934. update_foes(array($group_id));
  2935. }
  2936. }
  2937. /**
  2938. * Funtion to make a user leave the NEWLY_REGISTERED system group.
  2939. * @access public
  2940. * @param $user_id The id of the user to remove from the group
  2941. */
  2942. function remove_newly_registered($user_id, $user_data = false)
  2943. {
  2944. global $db;
  2945. if ($user_data === false)
  2946. {
  2947. $sql = 'SELECT *
  2948. FROM ' . USERS_TABLE . '
  2949. WHERE user_id = ' . $user_id;
  2950. $result = $db->sql_query($sql);
  2951. $user_row = $db->sql_fetchrow($result);
  2952. $db->sql_freeresult($result);
  2953. if (!$user_row)
  2954. {
  2955. return false;
  2956. }
  2957. else
  2958. {
  2959. $user_data = $user_row;
  2960. }
  2961. }
  2962. if (empty($user_data['user_new']))
  2963. {
  2964. return false;
  2965. }
  2966. $sql = 'SELECT group_id
  2967. FROM ' . GROUPS_TABLE . "
  2968. WHERE group_name = 'NEWLY_REGISTERED'
  2969. AND group_type = " . GROUP_SPECIAL;
  2970. $result = $db->sql_query($sql);
  2971. $group_id = (int) $db->sql_fetchfield('group_id');
  2972. $db->sql_freeresult($result);
  2973. if (!$group_id)
  2974. {
  2975. return false;
  2976. }
  2977. // We need to call group_user_del here, because this function makes sure everything is correctly changed.
  2978. // A downside for a call within the session handler is that the language is not set up yet - so no log entry
  2979. group_user_del($group_id, $user_id);
  2980. // Set user_new to 0 to let this not be triggered again
  2981. $sql = 'UPDATE ' . USERS_TABLE . '
  2982. SET user_new = 0
  2983. WHERE user_id = ' . $user_id;
  2984. $db->sql_query($sql);
  2985. // The new users group was the users default group?
  2986. if ($user_data['group_id'] == $group_id)
  2987. {
  2988. // Which group is now the users default one?
  2989. $sql = 'SELECT group_id
  2990. FROM ' . USERS_TABLE . '
  2991. WHERE user_id = ' . $user_id;
  2992. $result = $db->sql_query($sql);
  2993. $user_data['group_id'] = $db->sql_fetchfield('group_id');
  2994. $db->sql_freeresult($result);
  2995. }
  2996. return $user_data['group_id'];
  2997. }
  2998. /**
  2999. * Gets user ids of currently banned registered users.
  3000. *
  3001. * @param array $user_ids Array of users' ids to check for banning,
  3002. * leave empty to get complete list of banned ids
  3003. * @return array Array of banned users' ids if any, empty array otherwise
  3004. */
  3005. function phpbb_get_banned_user_ids($user_ids = array())
  3006. {
  3007. global $db;
  3008. $sql_user_ids = (!empty($user_ids)) ? $db->sql_in_set('ban_userid', $user_ids) : 'ban_userid <> 0';
  3009. // Get banned User ID's
  3010. // Ignore stale bans which were not wiped yet
  3011. $banned_ids_list = array();
  3012. $sql = 'SELECT ban_userid
  3013. FROM ' . BANLIST_TABLE . "
  3014. WHERE $sql_user_ids
  3015. AND ban_exclude <> 1
  3016. AND (ban_end > " . time() . '
  3017. OR ban_end = 0)';
  3018. $result = $db->sql_query($sql);
  3019. while ($row = $db->sql_fetchrow($result))
  3020. {
  3021. $user_id = (int) $row['ban_userid'];
  3022. $banned_ids_list[$user_id] = $user_id;
  3023. }
  3024. $db->sql_freeresult($result);
  3025. return $banned_ids_list;
  3026. }
  3027. ?>